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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The example is safe: if the
shared_ptrconstructor throws an exception, itdelete‘s its pointer argument before throwing (draft standard, 20.9.11.2.1).Whether
createshould return ashared_ptrdepends on what its clients may reasonably want to do with its result. If all they ever do is wrap it in ashared_ptr, then return that for extra safety. (Yes,shared_ptrmay introduce some coupling.)