介绍
问题源于对条件接口(interface)的需求。可能是因为我陷入了 XY 问题,但(底线)我最终需要一个共享指针,该指针将(基于运行时选择)管理或不管理(拥有或不拥有)资源。
到目前为止的工作
以下是关于非拥有共享指针的一些想法
使用新的展示位置,例如:
struct MyStruct {}; MyStruct ms1; std::shared_ptr<MyStruct> sp(new(&ms1) MyStruct);
使用虚拟删除器
std::shared_ptr<MyStruct> spn(new MyStruct, [](MyStruct*){});
问题
- 是否有标准建议方法?
- 有“不做”的规定吗?
- 至少有更好的方法吗?
注意事项
我的类布局(将使用非拥有共享指针的地方)如下所示:
template<typename T>
struct blah
{
shared_ptr<T> _m;
};
现在,_m
成员可能会也可能不会拥有基于运行时选择的资源。我不使用 weak_ptr
的原因是 _m
实际上可能是一个拥有指针。
最佳答案
新放置显然是 UB,因为它会在您的代码段中尝试删除堆栈中的某些内容。空删除器版本可以工作,但会分配一个引用计数 block 。
诀窍是使用 shared_ptr
的疯狂(好吧,别名)构造函数:
template< class Y >
shared_ptr( const shared_ptr<Y>& r, T *ptr );
构造一个 shared_ptr
拥有 r
拥有的内容,但指向 ptr
指向的内容,即:
std::shared_ptr<MyStruct> sp(std::shared_ptr<MyStruct>(), p);
这由标准保证noexcept
,并且不会分配任何东西。该标准甚至有一条注释说
[ Note: This constructor allows creation of an empty
shared_ptr
instance with a non-null stored pointer. —end note ]
关于c++ - 我可以拥有非拥有的共享指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26216522/