gpt4 book ai didi

c++ - 从同一个指针构造两个 shared_ptr 对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:41:13 24 4
gpt4 key购买 nike

我有一个来自“C++ 标准库扩展”的问题:

Exercise 6
I said in Section 2.4.2 that you shouldn't construct two shared_ptr objects from the same pointer. The danger is that both shared_ptr objects or their progeny will eventually try to delete the resource, and that usually leads to trouble. In fact, you can do this if you're careful. It's not particularly useful, but write a program that constructs two shared_ptr objects from the same pointer and deletes the resource only once.

下面是我的回答:

template <typename T>
void nonsence(T*){}
struct SX {
int data;
SX(int i = 0) :
data(i) {
cout << "SX" << endl;
}
~SX() {
cout << "~SX" << endl;
}
};
int main(int argc, char **argv) {
SX* psx=new SX;
shared_ptr<SX> sp1(psx),sp2(psx,nonsence<SX>);
cout<<sp1.use_count()<<endl;
return 0;
}

但我认为这不是一个好的解决方案——因为我不想通过使用构造函数来解决它。谁能给我一个更好的?谢谢,请原谅我糟糕的英语。

最佳答案

您需要做的就是从第一个 shared_ptr 构造第二个 shared_ptr

shared_ptr<SX> sp1( new SX );
shared_ptr<SX> sp2( sp1 );

只有当所有指向它的共享指针被销毁时,创建的 SX 才会被正确删除。

关于c++ - 从同一个指针构造两个 shared_ptr 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/871574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com