【发布时间】:2018-06-15 18:25:57
【问题描述】:
我有一个shared_ptr<MyProto>,我传递了它。最终,在某些情况下,我想将原始指针传递给一个函数,然后该函数成为内存所有者。在这些情况下,shared_ptr 不再负责释放内存,因为我调用的函数取得了所有权。如何让shared_ptr 失去所有权?
我想让 shared_ptr 失去所有权的原因是我想使用协议缓冲区的 AddAllocated 功能,该功能采用已分配的指针并承担它的所有权。
例子:
shared_ptr<MyProto> myProtoSharedPtr = // by this point this is the last reference to the heap allocated MyProto
// I want to add it to a collection and serialize the collection without copying
CollectionProto collectionProto;
collectionProto.mutable_my_proto().AddAllocated(myProtoSharedPtr.get()); // at this point collectionProto took ownership of the memory
std::string serialization = collectionProto.SerializeAsString();
// bad: myProtoSharedPtr.get() will be freed twice
【问题讨论】:
-
你为什么使用共享指针?
-
这没有意义..这个
shared_ptr要释放所有权,其他shared_ptrs共享所有权怎么样? -
您必须从拥有它的每个
std::shared_ptr释放所有权。这对 imo 来说不是一件很安全的事情。如果错过了怎么办? -
@Hitobat 如果这是最后一个 shared_ptr,这将释放内存。
-
你想要的几乎是不可能的,因为上面提到的关于共享所有权的原因,但也因为你不知道内存是如何分配的。如果共享指针是使用
make_shared创建的,您可能有一个内存块同时保存对象和控制块,因此您必须用对象销毁控制块,但如果它是一个,您会怎么做或者如果你只有一个指向对象的指针?
标签: c++ c++11 protocol-buffers shared-ptr