When is object pointed by std::shared_ptr deleted?

人盡茶涼 提交于 2019-12-08 11:58:34

问题


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();
}

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?

Is this concept good?


回答1:


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();
}

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.




回答2:


From this reference, the object is deleted when one of the following is true.

  • the last remaining shared_ptr owning the object is destroyed.

  • the last remaining shared_ptr owning the object is assigned another pointer via operator= or reset().

With respect to your specific situation, when the shared pointer is popped off the stack, if that is the last one referencing the object, then the object is destroyed when the popped-off element goes out of scope.

Note that if you extract a raw pointer to the same object and explicitly delete the object first, then you are invoking undefined behavior because delete may be called twice on the same object.



来源:https://stackoverflow.com/questions/23671945/when-is-object-pointed-by-stdshared-ptr-deleted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!