首页 > 解决方案 > 为什么 std::shared_ptr 在使用 std::static_pointer_cast 时会破坏两次?

问题描述

我的代码如下:

#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;
}

它打印:

ccccdddddddd

这表明析构函数被调用了两次。为什么会发生这种情况以及如何解决?

标签: c++castingshared-ptr

解决方案


没有什么可以修复的。每个对象不会调用析构函数两次。相反,您没有跟踪所有构造函数。将跟踪添加到复制和移动构造函数,如

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

通过此更改,您的输出应该是

ccccMCCCdddddddd

表示 8 个构造函数调用和 8 个析构函数调用。


推荐阅读