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_classobject, even ifshared_ptrcould not allocate memory.According to the C++11 standard (20.7.2.2.1), in the
shared_ptrconstructor:In the constructor version that takes a user-defined deleter, the deleter will be used instead.
Boost documentation specifies the same.