C++ Memory Leak Using STL Containers

前端 未结 3 2061
天命终不由人
天命终不由人 2020-12-12 04:55

The following code is giving me a memory leak (using Visual Studio):

#define _CRTDBG_MAP_ALLOC
#include 
#include 
#include &         


        
3条回答
  •  情深已故
    2020-12-12 05:22

    std::vector listeners; will not free the members of Listeners. You'd have to delete each of the listeners that are inside the vector, using something like:

    for (int i = 0; i < listeners.size(); i++) delete listeners[i]
    

    Personally, I avoid such issues by using smart pointers:

    std::vector> listeners
    

    _CrtDumpMemoryLeaks detects leaks by counting news and making sure they all match. Because subject never goes out of scope, I'm guessing it is counted as an outstanding reference. Try int main(void) {{Subject subject;}_CrtDumpMemoryLeaks(); return 1}

提交回复
热议问题