What happens if the shared_ptr constructor fails?

If I understand correctly, when shared_ptr (from boost, tr1, std, whatever) is initialized with a pointer to a newly allocated object, the shared_ptr constructor allocates a small amount of memory to store the reference account for the pointer it manages. What happens if this distribution 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 there be a leak of the my_class object if shared_ptr cannot allocate memory for its reference counter? Or is the shared_ptr constructor responsible for deleting the object?

+8
c ++ memory-management smart-pointers
source share
1 answer

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

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

Throws: bad_alloc or an exception thrown by the implementation when a resource other than memory could not be received.

Exception safety: if an exception is thrown, deletion p is called.

In a constructor version that accepts a user-defined deleter, a debiter is used instead.

The Boost documentation indicates the same.

+7
source share

All Articles