Search code examples
c++boostscoped-ptr

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

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.