2017-05-25 195 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

相關問題