删除 std::shared

编程入门 行业动态 更新时间:2024-10-25 12:24:22
本文介绍了删除 std::shared_ptr 而不破坏托管对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我处于以下情况:

struct container { data* ptr; }; void someFunc(container* receiver /* wants to be filled */) { auto myData = createData(); // returns shared_ptr<data> receiver->ptr = myData.get(); }

生成该数据的函数和接收它的对象是两个不同库的一部分,我无法修改其源代码.我必须处理这些数据类型,对此我无能为力.

所以我必须实现一个函数来获取一些数据,然后将一个指向该数据的指针传递给一个对象.我的问题是创建我的数据的函数返回一个 shared_ptr 实例给它.需要数据的对象只接受指向它的原始指针.

So I have to implement a function that acquires some data, then passes a pointer to that data to an object. My problem is that the function that creates my data, returns a shared_ptr instance to it. The object that needs the data will only accept a raw pointer to it.

如您所见,我在 shared_ptr 上调用 get() 以获取原始指针并将其传递给接收对象.如果我没记错的话,shared_ptr 会在超出范围时递减引用计数.所以在这种情况下,这意味着它会在函数返回后立即销毁我的数据,因为引用计数将达到 0.

As you can see, I call get() on the shared_ptr to get the raw pointer and pass it to the receiving object. If I'm not mistaken, then a shared_ptr decrements the reference count whenever it goes out of scope. So in this case, that means that it would destroy my data as soon as the function returns, since the reference count would reach 0.

那么如何在不破坏托管对象的情况下摆脱 shared_ptr 实例?我将数据传递给的对象(为简单起见,用容器"结构说明)确实负责其析构函数内部的内存清理,因此我不需要任何引用计数或类似的东西.我不想再有任何东西来监视分配的数据(除了接收指向它的指针的对象).我想摆脱shared_ptr,只有一个指向分配数据的原始指针,我可以将其传递给接收对象.

So how can I get rid of the shared_ptr instance without destroying the managed object? The object which I pass the data to (illustrated with the "container" struct for simplicity) does take care of the memory cleaning inside its destructor, so I don't need any reference counting or anything like that. I don't want anything to watch over that allocated data anymore (except the object that receives a pointer to it). I want to get rid of the shared_ptr, and only have a raw pointer to the allocated data, which I can pass to the receiving object.

这可能吗?

推荐答案

static std::map m<data *, std::shared_ptr<data> >; struct container { data* ptr; }; void someFunc(container* receiver /* wants to be filled */) { auto myData = createData(); // returns shared_ptr<data>, I can't do anything about it receiver->ptr = myData.get(); m[receiver->ptr] = myData; } void someOtherFunc(container* receiver) { // delete receiver->ptr; m.erase(receiver->ptr); }

这通过地图延长了 shared_ptr 的生命.

This elongates the life of shared_ptr through a map.

更多推荐

删除 std::shared

本文发布于:2023-07-30 00:23:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1244942.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:std   shared

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!