#include <iostream>
#include <boost/shared_ptr.hpp>
class implementation
{
public:
~implementation() { std::cout <<"destroying implementation\n"; }
void do_something() { std::cout << "did something\n"; }
};
void test()
{
boost::shared_ptr<implementation> sp1(new implementation());
std::cout<<"The Sample now has "<<sp1.use_count()<<" references\n";
boost::shared_ptr<implementation> sp2 = sp1;
std::cout<<"The Sample now has "<<sp2.use_count()<<" references\n";
sp1.reset();
std::cout<<"After Reset sp1. The Sample now has "<<sp2.use_count()<<" references\n";
sp2.reset();
std::cout<<"After Reset sp2.\n";
}
int main()
{
test();
}
運行結果不清楚低於:東西在這個shared_ptr的例子
$ ./a.out
The Sample now has 1 references
The Sample now has 2 references
After Reset sp1. The Sample now has 1 references
destroying implementation
After Reset sp2.
請檢查上面的代碼。我不清楚的第一件事是,下面的句子是什麼意思?所以sp1是一個指針?一個函數?或者一個指向函數的指針?和new implementation()
意味着什麼? sp1()的參數?
boost::shared_ptr<implementation> sp1(new implementation());
第二個問題是,destroying implementation
給出的sp1.reset()
和sp2.reset()
的結果。但是,如果sp1.reset()
被註釋掉,那麼結果將是:
$ ./a.out
The Sample now has 1 references
The Sample now has 2 references
After Reset sp1. The Sample now has 2 references
After Reset sp2.
destroying implementation
如果我們只註釋掉sp2.reset()
,那麼結果將是:
$ ./a.out
The Sample now has 1 references
The Sample now has 2 references
After Reset sp1. The Sample now has 1 references
After Reset sp2.
destroying implementation
所以沒有必要同時調用sp1.reset()
和sp2.reset()
釋放shared_ptr,我是對不對?
你不需要調用'reset'來釋放指針**,你可以使用'reset'來改變智能指針當前指向的內容。您可以將它想象爲一個常規指針的賦值運算符。 –
如果你不知道'new x()'做了什麼,你需要了解指針。如果你不知道共享指針是什麼,你需要了解智能指針。沒有簡單的答案比實際閱讀更有益。 – chris
在試圖理解C++'shared_ptr'之前,至少可以想象你應該先學習另一種語言。根據「Python自動執行的操作」或「在語言X中執行相同的操作'try'/ finally'執行相同的操作,這要比從頭開始解釋它要容易得多。」 – abarnert