作者:丝家发艺 | 来源:互联网 | 2022-12-13 19:58
我有一个shared_ptr
我经过的地方.最终,在某些情况下,我想将原始指针传递给一个函数,然后该函数成为内存所有者.在这些情况下,shared_ptr
由于我调用的函数取得了所有权,因此不再负责释放内存.如何让shared_ptr
失去所有权?
我想拥有shared_ptr
失去所有权的原因是我想使用协议缓冲区的AddAllocated功能,它接受已经分配的指针并承担它的所有权.
例:
shared_ptr 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
AchimGuetlei..
6
你可以使用a unique_ptr
,无论如何更适合传递内存:
unique_ptr 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();
Galik..
6
我认为你可以通过共享一个像这样的独特指针来实现你想要做的事情:
std::shared_ptr> myProtoSharedUniquePtr;
访问它会更间接:
(*myProtoSharedUniquePtr)->do_stuff();
但你可以像这样拥有所有权:
CollectionProto collectionProto;
collectionProto.mutable_my_proto().AddAllocated(myProtoSharedUniquePtr->release()); // at this point collectionProto took ownership of the memory
std::string serialization = collectionProto.SerializeAsString();
但是我会质疑你为什么要使用a std::shared_ptr
开头.使用a的原因std::shared_ptr
是当你无法控制谁将最后访问它时,所以每个人都可以保持活着直到完成.因此,能够保证所有当前std::shared_ptr
实例不再使用是不寻常的.
你确定std::unique_ptr
你的需求不会更好吗?
1> AchimGuetlei..:
你可以使用a unique_ptr
,无论如何更适合传递内存:
unique_ptr 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();
2> Galik..:
我认为你可以通过共享一个像这样的独特指针来实现你想要做的事情:
std::shared_ptr> myProtoSharedUniquePtr;
访问它会更间接:
(*myProtoSharedUniquePtr)->do_stuff();
但你可以像这样拥有所有权:
CollectionProto collectionProto;
collectionProto.mutable_my_proto().AddAllocated(myProtoSharedUniquePtr->release()); // at this point collectionProto took ownership of the memory
std::string serialization = collectionProto.SerializeAsString();
但是我会质疑你为什么要使用a std::shared_ptr
开头.使用a的原因std::shared_ptr
是当你无法控制谁将最后访问它时,所以每个人都可以保持活着直到完成.因此,能够保证所有当前std::shared_ptr
实例不再使用是不寻常的.
你确定std::unique_ptr
你的需求不会更好吗?