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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With