The problem is that raw new does not define ownership. If I am new to the object and return it, to whom does it belong? Does it create a function / object or perform a call function? If you return smart pointers (std :: shared_ptr and std :: unique_ptr), you specify ownership.
Not specifying ownership is one of the easiest ways to leak memory. Itβs the hardest part for me, even with professional programmers, forcing people to understand property and work with it. This is largely prevented by using good types (smart pointers) that define ownership only by existing.
type* function(); // Unspecified ownership. // Must be well documented and all users must read // and follow the documentation. std::unique_ptr<type> function(); // Calling function owns returned pointer. // Single ownership. std::shared_ptr<type> function(); // Calling function owns returned pointer. // Shared ownership. Can have multiple owners. std::weak_ptr<type> function(); // Calling function references returned pointer. // Must lock pointer to get owned object, if not deleted. // Shared ownership. Can have multiple owners.
These various types of pointers express ownership of existing ones only, unlike original pointers.
As for new , always wrong. This is an excessive generalization. std::shared_ptr is created using the global function std::make_shared . Starting with C ++ 11 there is no std::make_unique , but this will be fixed in C ++ 14. The only way to create std::unique_ptr is to use the new one and immediately assign a pointer to std::unique_ptr .
There are also places where you need a raw pointer and manually use new and delete , but they are usually very low, and most programmers rarely come across them.
Which really annoys me is your code, not that you are using new , but you are looking for a pointer and assigning it a link. It would be almost impossible to guarantee that the destructor would ever be called. It also tends to leak memory, although if a static variable is assigned, it will be freed when the program terminates, so you really don't look at a memory leak.
MyClass& MyClass::MyInstance() { static MyClass & myLocalVariable = * new MyClass(); return myLocalVariable ; }
I would prefer to create a static variable by value, not by reference. This prevents the object from being placed in a heap. Depending on MyClass , you can also enable the mapping of an object into memory from an executable file without the need to run any code to initialize it.
MyClass& MyClass::MyInstance() { static MyClass myLocalVariable(); return myLocalVariable ; }