Don't!
Use automatic storage...
The new
operator is designed to implement dynamic allocation (what you are calling "on the heap") and, although you can provide your own allocator, as such you cannot twist it into obeying the scoping rules of objects of automatic storage duration (what you are calling "on the stack").
Instead, write:
MyType myobject; // automatic storage duration
...or smart pointers...
Or, if you don't mind dynamic storage duration but only want to avoid later manual destruction, use smart pointers:
std::unique_ptr<MyType> myptr(new myobject()); // unique, dynamic storage duration
std::shared_ptr<MyType> myptr(new myobject()); // shared, dynamic storage duration
Both of these are found in C++11 (std::
) and Boost (boost::
).
... or placement new
?
Another approach might be placement new but this is a dark and dangerous path to travel that I would certainly not recommend at this stage. Or, frankly, any stage... and you'd usually still need to do manual destruction. All you gain is using the keyword new
, which seems pointless.