使shared_ptr失去内存所有权 [英] Making shared_ptr lose ownership of memory

查看:101
本文介绍了使shared_ptr失去内存所有权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 shared_ptr< MyProto> ,我可以通过它。最终,在某些情况下,我想将原始指针传递给一个函数,然后该函数成为内存所有者。在这些情况下, shared_ptr 不再负责释放内存,因为我调用的函数已拥有所有权。如何获得 shared_ptr 失去所有权?

I have a shared_ptr<MyProto> which I pass around. Eventually, in certain situations, I want pass the raw pointer to a function which then becomes the memory owner. In those cases the shared_ptr isn't responsible anymore for freeing the memory because the function I call took ownership. How do I get the shared_ptr to lose ownership?

我想拥有 shared_ptr 失去所有权是因为我想使用协议缓冲区的AddAllocated功能,该功能采用一个已分配的指针并假定其所有权。

The reason I want to have the shared_ptr lose ownership is that I want to use protocol buffer's AddAllocated functionality which takes an already allocated pointer and assumes ownership of it.

示例:

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


推荐答案

我认为您可以通过共享一个唯一的
指针
来实现您想要的工作,

I think you can achieve what you want to do by sharing a unique pointer like this:

std::shared_ptr<std::unique_ptr<MyProto>> myProtoSharedUniquePtr;

访问它会更间接:

(*myProtoSharedUniquePtr)->do_stuff();

但是您可以像这样获得所有权:

But you could take ownership like this:

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

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

However I would question why you are using a std::shared_ptr to begin with. The reason to use a std::shared_ptr is when you have no control over who will be last to access it, so each one gets to keep it alive until they are done. So it would be unusual to be able to guarantee all current std::shared_ptr instances are no longer in use.

您确定 std :: unique_ptr 会满足您的需求吗?

Are you sure a std::unique_ptr would not be better for your needs?

这篇关于使shared_ptr失去内存所有权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆