Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top