什么时候删除了std :: shared_ptr指向的对象? [英] When is object pointed by std::shared_ptr deleted?

查看:230
本文介绍了什么时候删除了std :: shared_ptr指向的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的图书馆中,我使用std:shared_ptr`s来保存我正在使用的通信对象。我有创建这些指针的模板函数。它返回原始指针,因此应用程序可以使用这些对象,而无需进行引用计数(严格的实时应用程序)。

In my library, I use std:shared_ptr`s to hold communication objects, I am working with. I have template function creating those pointers. It returns raw pointers so application could use those objects, without overhead with reference counting (strict realtime application).

template<typename COBTYPE>
inline COBTYPE* CLink::createCob(COBTYPE cob) {
  std::shared_ptr<CCob> c(cob);

  if(c->init(this)!=OK){
    trace(ERROR,"Cannot add cob, failed to initialize\n");
    return NULL;
  }
  mCobs.push_back(c); //vector of my pointers
  return (COBTYPE*) c.get();
}

如果我调用函数,我不确定何时删除对象作为
link.createCob(new CobOfSomeTypo cob())吗?
当必须从堆栈中弹出时,使用shared_ptr可以防止删除cob对象吗?

I am in doubt, when the object will be deleted, if I call function as link.createCob(new CobOfSomeTypo cob()) ? Will use of shared_ptr prevent delete of cob object when it will have to pop from stack?

这个概念好吗?

推荐答案

当不再有共享指针共享所有权时,将删除共享指针共享所有权的对象

The object of which a shared pointer shares ownership is deleted when there are no more shared pointers sharing ownership, e.g. typically in the destructor of some shared pointer (but also in an assignment, or upon explicit reset).

(请注意,可能存在许多不同的共享指针类型共享同一对象的所有权!)

(Note that there may be shared pointers of many different types sharing ownership of the same object!)

也就是说,您的代码有问题。也许这样更好:

That said, your code has issues. Perhaps it might be better like this:

// Requirement: C must be convertible to CCob

template <typename C>
C * CLink::createCob()
{
    auto p = std::make_shared<C>();

    if (p->init(this) != OK) { return nullptr; }

    mCobs.push_back(std::move(p));

    return mCobs.back().get();
}

用法如下: link.createCob< CobOfSomeTypo>()。不过,这取决于您是否需要获得现有指针的所有权

The usage would then be: link.createCob<CobOfSomeTypo>(). It depends, though, on whether you need to be able to take ownership of existing pointers. That itself would be something worth fixing, though.

也有可能(但无法从您的问题中得知)您实际上根本不需要共享指针,并且可以简单地工作具有唯一的指针。

It's also possible (but impossible to tell from your question) that you dont actually need shared pointers at all and could simply work with unique pointers.

这篇关于什么时候删除了std :: shared_ptr指向的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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