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

后端 未结 5 1808
花落未央
花落未央 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:55

    You haven't resolved any memory leaks. If you new, then you must delete. All you did was dereference the pointer, it still needs to be deleted. You can resolve memory leaks by creating local objects and returning by value, or using smart pointers. 99 times out of 100, I prefer the return by value option.

    Now, like many beginners, the idea of returning large objects by value probably scares your perf-centric mind. Read this to allay your fears.

提交回复
热议问题