使shared_ptr失去内存的所有权

yto*_*ano 4 c++ shared-ptr protocol-buffers c++11

我有一个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
Run Code Online (Sandbox Code Playgroud)

Ach*_*ein 6

你可以使用a unique_ptr,无论如何更适合传递内存:

unique_ptr<MyProto> myProtoSharedPtr = // create MyPorto object

CollectionProto collectionProto;

// unique_ptr::release returns the pointer and
// releases the ownership of the MyProto object
collectionProto.mutable_my_proto().AddAllocated(myProtoSharedPtr.release());

std::string serialization = collectionProto.SerializeAsString();
Run Code Online (Sandbox Code Playgroud)


Gal*_*lik 6

我认为你可以通过共享一个像这样的独特指针来实现你想要做的事情:

std::shared_ptr<std::unique_ptr<MyProto>> myProtoSharedUniquePtr;
Run Code Online (Sandbox Code Playgroud)

访问它会更间接:

(*myProtoSharedUniquePtr)->do_stuff();
Run Code Online (Sandbox Code Playgroud)

但你可以像这样拥有所有权:

CollectionProto collectionProto;
collectionProto.mutable_my_proto().AddAllocated(myProtoSharedUniquePtr->release()); // at this point collectionProto took ownership of the memory
std::string serialization = collectionProto.SerializeAsString();
Run Code Online (Sandbox Code Playgroud)

但是我会质疑你为什么要使用a std::shared_ptr开头.使用a的原因std::shared_ptr是当你无法控制谁将最后访问它时,所以每个人都可以保持活着直到完成.因此,能够保证所有当前std::shared_ptr实例不再使用是不寻常的.

你确定std::unique_ptr你的需求不会更好吗?