Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if a shared_ptr's constructor fails?

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?

like image 465
bythescruff Avatar asked Aug 12 '12 12:08

bythescruff


1 Answers

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.

like image 96
interjay Avatar answered Sep 17 '22 02:09

interjay