Question

I am using scoped_ptr inside small functions like this. so that I don't have to call delete. Is this an overkill for this usage? My team members prefer raw pointers and delete. What is the cost of using scoped_ptr if this happens to be used in a very critical path? Shouldn't this be in-lined and be exactly equivalent to just using normal delete in optimized binary?

void myfunc()
{
  boost::scoped_ptr<myobj> objptr = someFactory::allocate();
  callsomeotherfunc(objptr.get());
}
Was it helpful?

Solution

I am unsure of the performance hit, but using scoped_ptr here ensures myfunc() is exception safe: if callsomeotherfunc() throws an exception the dynamically allocated memory will still be freed. If scoped_ptr was not used and callsomeotherfunc() could throw then the function would have to be structured similar to this:

void myfunc()
{
    myobj* objptr = someFactory::allocate();

    try
    {
        callsomeotherfunc(objptr);
        delete objptr;
    }
    catch (const some_exception&)
    {
        delete objptr;
        throw;
    }
}

This is error prone as all future modifications of the function would need to ensure that delete objptr; is invoked on all possible exit points.

OTHER TIPS

I would not use scoped_ptr for that purpose, but rather unique_ptr in C++11 and auto_ptr in older compilers, both of which are equivalent for your particular use case. As of whether it is overkill, no, it is not, it is the only option to providing exception safety (say anything in the code of either myfunc or callsomeotherfunc throws, you want the memory to be released). Performance wise, the three options are equivalent to having a delete call at the end of the function in the case where exceptions are not thrown, and faster than having a try/catch block with a delete that rethrows the exception in the event of exceptions.

Additionally, it seems that you are allocating from a factory, in some designs that factory will have a deallocate operation that needs to be called, rather than delete. If that is the case, you might consider a different smart pointer (shared_ptr from the standard, which would be overkill if delete is the proper way of releasing the memory; or some short of managed_ptr for which you can also provide a deleter)

No, it is not. The benefit of using smart pointer (e.g. exception safety and automatic resource cleanup) is far higher than performance loss of using couple of additional bytes of memory and couple of additional CPU clocks needed for smart pointer creation, maintenance and destruction.

I think that the equivalent to scoped_ptr usage would be:

void myfunc()
{
  myobj* objptr = someFactory::allocate();
  try
  {
      callsomeotherfunc(objptr);
  }
  catch (...)
  {
      delete objptr;
      throw;
  }
  delete objptr;
}

I know which version I'd prefer to write...

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