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?
Look at the implementation of
make_shared(). It does this allocates a new object and creates ashared_ptrout of it.