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

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

    Yes there is a memory leak. The following code is executed with valgrind :

    #include 
    
    class my_class
    {
        public :
        my_class(void)
        {
            std::cout << "Constructor" << std::endl;
        }
         ~my_class(void)
        {
            std::cout << "Destructor" << std::endl;
        }
    };
    
    my_class& func(void)
    {
        my_class* c = new my_class;
        return *c;
    }
    
    int main(void)
    {
        my_class& var1 = func();
        // Question : I think there is no memory leak.
        // Answer : Yes there is a memory leak in func().
    }
    
    
    
    /shared/TOOLS/valgrind-3.6.1/bin/valgrind --leak-check=full ./main2.exe
    ==13004== Memcheck, a memory error detector
    ==13004== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
    ==13004== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info
    ==13004== Command: ./main2.exe
    ==13004==
    Constructor
    ==13004==
    ==13004== HEAP SUMMARY:
    ==13004==     in use at exit: 1 bytes in 1 blocks
    ==13004==   total heap usage: 1 allocs, 0 frees, 1 bytes allocated
    ==13004==
    ==13004== 1 bytes in 1 blocks are definitely lost in loss record 1 of 1
    ==13004==    at 0x4A06DC7: operator new(unsigned long) (vg_replace_malloc.c:261)
    ==13004==    by 0x400966: func() (in /home/toto/CppTest/main2.exe)
    ==13004==    by 0x4009BC: main (in /home/toto/CppTest/main2.exe)
    ==13004==
    ==13004== LEAK SUMMARY:
    ==13004==    definitely lost: 1 bytes in 1 blocks
    ==13004==    indirectly lost: 0 bytes in 0 blocks
    ==13004==      possibly lost: 0 bytes in 0 blocks
    ==13004==    still reachable: 0 bytes in 0 blocks
    ==13004==         suppressed: 0 bytes in 0 blocks
    ==13004==
    ==13004== For counts of detected and suppressed errors, rerun with: -v
    ==13004== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 7 from 7)
    

提交回复
热议问题