2010-09-30 71 views
11

關於boost::shared_ptr s的陷阱有幾個有趣的問題。在其中之一中,有一個有用的技巧是避免將boost::shared_ptr<Base>boost::shared_ptr<Derived>指向Derived類型的同一對象,因爲它們使用不同的引用計數並可能過早地破壞對象。做boost :: shared_ptr <T>和boost :: shared_ptr <const T>分享引用計數?

我的問題:boost::shared_ptr<T>boost::shared_ptr<const T>指向同一個T類型的對象是安全的,還是會導致同樣的問題?

+1

您能否提供基準/衍生聲明的參考? – fredoverflow 2010-09-30 07:07:09

+0

http://stackoverflow.com/questions/701456/what-are-potential-dangers-when-using-boostshared-ptr/716112#716112 – lytenyn 2010-09-30 07:11:51

+5

基地/派生是100%安全。使用'get()'是不安全的。這裏是沒有Base的類似情況:''shared_ptr ptr(new Derived),ptr2(ptr.get());' - unsafe。 – ybungalobill 2010-09-30 07:16:35

回答

18

這是完全安全的。

下面的代碼示例:

#include <iostream> 
#include <boost/shared_ptr.hpp> 

int main(int, char**) 
{ 
    boost::shared_ptr<int> a(new int(5)); 
    boost::shared_ptr<const int> b = a; 

    std::cout << "a: " << a.use_count() << std::endl; 
    std::cout << "b: " << b.use_count() << std::endl; 

    return EXIT_SUCCESS; 
} 

編譯和運行良好,並且是完全正確的。它輸出:

a: 2 
b: 2 

這兩個shared_ptr共享相同的引用計數器。


另外:

#include <iostream> 
#include <boost/shared_ptr.hpp> 

class A {}; 
class B : public A {}; 

int main(int, char**) 
{ 
    boost::shared_ptr<A> a(new B()); 
    boost::shared_ptr<B> b = boost::static_pointer_cast<B>(a); 

    std::cout << "a: " << a.use_count() << std::endl; 
    std::cout << "b: " << b.use_count() << std::endl; 

    return EXIT_SUCCESS; 
} 

行爲相同的方式。但您必須從未使用結構這樣建立自己的shared_ptr

boost::shared_ptr<A> a(new B()); 
boost::shared_ptr<B> b(static_cast<B*>(a.get())); 

a.get()給人的原始指針和損失大約引用計數的所有信息。這樣做,你會得到兩個不同的(不鏈接的)shared_ptr,它們使用相同的指針但是不同的引用計數器。

+0

謝謝,你是完全正確的。我對ybungalobill的例子有一個完全不同的誤解。謝謝你們倆! – lytenyn 2010-09-30 07:19:53

+1

我正要發表一個關於鑄造shared_pointer的問題,但在這裏得到了答案。謝謝。 – rjoshi 2010-11-06 00:24:21

相關問題