There are different approaches to this:
One of them "does not stand out on the heap":
SomeObject createSomeObject(){ return SomeObject(); }
If you do this, no one should free the object, and you have no sign of concern. A potential drawback is that SomeObject needs to be copied, but often this is a good solution and it should be standard. Do not use new / delete in user code; hide them inside constructor / destructor calls. (For example, perhaps SomeObject allocates some data on the heap inside and frees it when the object itself is destroyed).
The second approach is related, but uses a smart pointer:
std::shared_ptr<SomeObject> createSomeObject(){ return std::make_shared(new SomeObject()); }
it is like you are not returning a pointer, you are returning an object that is responsible for deleting everything that needs to be deleted. A smart pointer has claimed responsibility for your SomeObject instance and will delete it when necessary.
Depending on the circumstances, std::auto_ptr or std::unique_ptr .
In both cases, you rely on RAII , a very powerful idiom that every C ++ programmer should know. Resources should always be wrapped in local objects (not containing heaps) that are copied and moved as needed, and are responsible for cleaning up their internal resources.
source share