C ++智能指针计数器

时间:2015-07-23 06:40:20

标签: c++ c++11 smart-pointers

class Blob{
public:
    Blob();
    Blob(initializer_list<string> il);

private:
    shared_ptr<vector<string>> data;
};


Blob:: Blob() : data(make_shared<vector<string>>()) {}
Blob:: Blob(initializer_list<string> il) : data(make_shared<vector<string>>(il)) {}

Blob<string> b1; //empty Blob
{ //new scope
    Blob<string> b2 = {"a","b","the"};
    b1 = b2;//b1 and b2 share the same elements
}//b2 is destroyed, but the elements in b2 must not be destroyed
 //b1 points to the elements originally created in b2

我的问题是:为什么第4行的b1不应被销毁?在我看来,将一个 shared_pointer 分配给另一个增加右手操作数的计数,并减少左手操作数中的计数。 我想在line4上,b1变为0(计数器),所以它应该被销毁。

1 个答案:

答案 0 :(得分:2)

我假设你Blob班级相当于std::shared_ptr

{ // ----------------------------------------->  // Function scope

    Blob<string> b1; // ---------------------->  // b1 is empty : b1.use_count() == 0

    { // ------------------------------------->  // New scope

        Blob<string> b2(new std::string("Foo");  // b2 holds "Foo" : b2.use_count() == 1

        b1 = b2; // -------------------------->  // Assigning b2 to b1:
                                                 // b1 doesn't do anything because
                                                 // it was not holding any pointer.
                                                 // b1 now owns "Foo" as well
                                                 // and b1.use_count() == b2.use_count == 2

    } // ------------------------------------->  // b2 goes out of scope so it is removed
                                                 // and its reference counting is decreased.
                                                 // Since the count doesn't equal 0, nothing is done.

} // ----------------------------------------->  // b1 goes out of scope.
                                                 // The reference counting decreases again.
                                                 // Since the count is now 0,
                                                 // b1 deletes its internal pointer and releases "Foo".

在你的问题中,你似乎没有从它负责的指针中区分b1b1不是指针,因此当它超出范围时会被释放。