Does using references instead of pointers, resolve memory leaks in C++?

后端 未结 5 1815
花落未央
花落未央 2020-12-11 16:10

Most of memory leaks appear when a pointer of an object returned and programmer forgot to delete it.

for example:

class my_class
{
  ...
};

my_class         


        
5条回答
  •  孤城傲影
    2020-12-11 16:56

    Don't return raw pointers from functions; stick them in a smart pointer class such as unique_ptr or shared_ptr. Then you don't have to worry about deleting the allocated object.

    Also, in your second example, who is deleting the object allocated by func1()? Just because you return a reference instead of pointer doesn't mean freeing of allocated memory will happen magically.

提交回复
热议问题