Why can't a smart pointer call new() for me in its constructor?

Viewed 480

Is it possible to write a smart pointer which allocates the object itself in its constructor - instead of the developer having to call new? In other words, instead of writing:

std::unique_ptr<myClass> my_ptr(new myClass(arg1, arg2))

...one could write:

std::smarter_ptr<myClass> my_ptr(arg1, arg2)

Is the language syntax capable of expressing this? Would this be desirable? Hideous? I'm thinking in particular of protecting against this mistake (which I've made myself, of course):

myFunction(std::unique_ptr<myClass>(new myClass()), std::unique_ptr<myClass>(new myClass()))

...which risks leaking whichever object is allocated first if the second allocation happens and throws before the first object is safely ensconced in its smart pointer. But would a smarter pointer actually make this safe?

4 Answers
Related