Search code examples
c++castingshared-ptr

Why std::shared_ptr destruct twice when used std::static_pointer_cast?


my code is as below:

#include <iostream>
#include <memory>
#include <vector>
using namespace std;


struct A {
    A() { cout << "c"; }
    ~A() { cout << "d"; }
};

int main() {
    shared_ptr<void> a = make_shared<vector<A>>(3);
    auto b = static_pointer_cast<vector<A>>(a);
    b->push_back(A{});
    return 0;
}

It prints:

ccccdddddddd

which indicates that the destructor is called twice. Why this happens and how to fix it?


Solution

  • There is nothing to fix. The destructor is not being called twice per object. Rather, you are not tracking all of the constructors. Add tracking to the copy and move constructors, as in

    struct A {
        A() { cout << "c"; }
        A(const A &) { cout << "C"; }
        A(A &&) { cout << "M"; }
        ~A() { cout << "d"; }
    };
    

    With this change, your output should be

    ccccMCCCdddddddd
    

    indicating 8 constructor calls and 8 destructor calls.