c++ - 为什么 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
这表明析构函数被调用了两次。为什么会发生这种情况以及如何解决?
解决方案
没有什么可以修复的。每个对象不会调用析构函数两次。相反,您没有跟踪所有构造函数。将跟踪添加到复制和移动构造函数,如
struct A {
A() { cout << "c"; }
A(const A &) { cout << "C"; }
A(A &&) { cout << "M"; }
~A() { cout << "d"; }
};
通过此更改,您的输出应该是
ccccMCCCdddddddd
表示 8 个构造函数调用和 8 个析构函数调用。
推荐阅读
- android - 什么时候在 Kotlin 中传递函数类型是有益的?
- c# - 如果请求模型不正确,则 OnActionExecuting 不执行
- javascript - UnhandledPromiseRejectionWarning:SyntaxError:JSON 输入意外结束
- javascript - Angular 材质 mat-menu 重新加载页面
- python - 计算不包括开始日期的工作日,并使用 busday_count 包括结束日期
- firebase - 如何自动更新和回滚 Firebase 托管站点 + Cloud Run 服务?
- c# - 在托管服务中添加多个队列
- alert - 将 EMA 添加到警报查询
- redux - Slice 在 reducer 中的状态自引用
- powershell - PowerShell - xml 文件在同一元素名称上具有冲突的多个命名空间