删除 std::shared_ptr 而不破坏托管对象? [英] Delete std::shared_ptr without destroying the managed object?

查看:114
本文介绍了删除 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_ptr 而不破坏托管对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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