Although this is not entirely wrong, it is not a good idea.
MyClass& doSomething() { return *(new MyClass()); }
After you return, no one has the original pointer, so no one will ever be delete . * So this is a memory leak.
You almost never write new unless you have the appropriate delete -or constructor, or better, a smart pointer.
Meanwhile, this line in your source code:
MyClass a = doSomething();
... will still make a copy of the value. Assuming this is not a bug that needs to be fixed, why bother with allocating the heap of the object and returning a link to the copy and leak? Just return the object by value:
MyClass doSomething() { return MyClass(); }
Now you donβt have to worry about deleting anything because you never created anything on the heap.
Best practices can usually be summed up in the four letters of RAII: Initialization of Resources. (And the consequence is that destruction is liberation.) If you have something impossible or expensive to pass by value, then pass it by value. For instance:
unique_ptr<MyClass> doSomething() { return unique_ptr<MyClass>(new myClass()); } unique_ptr<MyClass> a = doSomething();
Now this is just a pointer that is being copied. The object itself is created inside doSomething and is deleted whenever a goes out of scope (or, if you pass it along with another variable, whenever it goes out of scope, etc.).
On the other hand, if MyClass is just a few easily copied values ββ**, just copy it.
* Unable to delete it; you can always take a pointer to a link and delete that. It's just that you are unlikely to ever do this, and it will look uncomfortable. If you want to pass pointers, go through the pointers. If you do not want to pass pointers, end the storage in the class and pass the class by value.
** By βeasy to copyβ I mean that itβs easy to copy them safely and that you actually do it. For example, a raw pointer or file descriptor is only a few bytes, and the default copy constructor will happily copy them for you ... but then you will get several links to the same object or heap file, and it is impossible to track which is responsible for deleting it or closing.