8

If I understand correctly, when a shared_ptr (from boost, tr1, std, whatever) is initialised with a pointer to a freshly-allocated object, the shared_ptr's constructor allocates a small amount of memory to hold a reference count for the pointer it manages. What happens if that allocation fails? In the following code:

class my_class {};
void my_func(shared_ptr<my_class> arg);

int main(int argc, char* argv[])
{
    my_func(shared_ptr<my_class>(new my_class()));
    return 0;
}

...will the my_class object be leaked if the shared_ptr fails to allocate memory for its reference count? Or does shared_ptr's constructor take responsibility for deleting the object?

1 Answer 1

7

Your code will not leak the my_class object, even if shared_ptr could not allocate memory.

According to the C++11 standard (20.7.2.2.1), in the shared_ptr constructor:

Throws: bad_alloc, or an implementation-defined exception when a resource other than memory could not be obtained.

Exception safety: If an exception is thrown, delete p is called.

In the constructor version that takes a user-defined deleter, the deleter will be used instead.

Boost documentation specifies the same.

1
  • Cheers. I did fire up Google but didn't find an answer. One of these days I'll learn to check the source - ie the standard. :-) Aug 13, 2012 at 7:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.