Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it an overkill to use scoped_ptr in simple cases?

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());
}
like image 894
balki Avatar asked Apr 27 '12 12:04

balki


2 Answers

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.

like image 148
hmjd Avatar answered Nov 07 '22 09:11

hmjd


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)

like image 26
David Rodríguez - dribeas Avatar answered Nov 07 '22 08:11

David Rodríguez - dribeas