c++memory-leaksshared-ptrexception-safe

safe std::tr1::shared_ptr usage


Is this approach unsafe?

#include <tr1/memory>

Foo * createFoo()
{
  return new Foo(5);
}

int main()
{
  std::tr1::shared_ptr<Foo> bar(create());

  return 0;
}

Or would it be preferable for createFoo to return a shared_ptr<Foo> object?


Solution

  • The example is safe: if the shared_ptr constructor throws an exception, it delete's its pointer argument before throwing (draft standard, 20.9.11.2.1).

    Whether create should return a shared_ptr depends on what its clients may reasonably want to do with its result. If all they ever do is wrap it in a shared_ptr, then return that for extra safety. (Yes, shared_ptr may introduce some coupling.)