2017-05-25 45 views
0

我有一个关于std :: shared_ptr的非常基本的问题。如果我有一些将std :: shared_ptr作为函数参数传递的首选方式是什么?

std::shared_ptr<A> p; 

,其中A类的一些在我的代码中定义的,什么是传递这个性病的首选方式:: shared_ptr的作为函数参数?它使一个有意义的定义我的功能,做一些与A级这样的实例:

void func(A &a); 

,并通过* p来这些功能,然后将“一个”回的std :: shared_ptr的有shared_from_this()如果需要的话?有没有理由这样做,常见的做法是什么?或者我应该通过shared_ptr的为这样的说法:

void func(std::shared_ptr<A> p); //thread safe 
void func(const std::shared_ptr<A> & p); //not thread safe 

在我的项目,我可以使用这两种方案中的大部分功能,但我的同事说,第一种选择是更好,因为基准(A &)总是比指针(shared_ptr或A *)更好,因为引用语义意味着参数不为null。

+1

可能重复的[我应该通过共享\ _ptr通过引用?](https://stackoverflow.com/questions/8385457/should-i-pass-a-shared-ptr-by-reference) – syntagma

+0

不完全因为这并没有真正解决第一种选择(通过引用传递指出),但肯定包含了一些适当的思想。 –

回答

1

如果你已经有了一个共享指针,没有意义不通过shared_ptr,但是通过shared_from_this创建一个新的。这很简单,并没有为你赚取任何收入。

通常的建议是,如果函数需要复制副本(例如,用于存储对象)并通过const引用传递(如果函数只需“查看”对象),则按值传递对象。

这也适用于共享指针。

因此,例如,

// Here func in the end needs a copy of the shared_ptr, so pass by value 
// the caller can decide whether he wants to move or a copy it in 
struct Example { 
    shared_ptr<A> m_a; 
    void func (shared_ptr<A> a) { 
    m_a = move (a); 
    } 
}; 

// Here func needs only a reference, so only pass a reference 
void func (shared_ptr<A> const & a) { 
    a->callme(); 
} 

// If func needs to see only an object of type A, i.e. does not 
// need a pointer, it makes 
// more sense to pass an A & or A const & 
void func (A const & a) { 
    a.callme(); 
} 

我无法想象通过引用传递shared_ptr会导致线程安全问题,可以通过传递值来避免的问题。当然,你应该避免在不保存任何地方共享指针副本的线程中引用共享指针。然而,只要线程拥有共享指针的副本,就可以在该线程中自由地传递对该共享指针的引用。

+0

你确定,你没有混合'A const'和'const A'? – Koban

+2

'const'和'const A'是一样的。 – JohnB

相关问题