如何真正删除矢量

JBR*_*RPG 8 c++ memory-leaks memory-management vector

我对C++内存管理很陌生,因为与C不同,释放所有内存还有更多障碍.

我试图成功删除任何类型的矢量指针(即矢量*数据)

/** 
 * We test the program in accessing vectors
 * with dynamic storage
**/
#include <iostream>
#include <vector> // you must include this to use vectors

using namespace std;

int main (void){
    // Now let's test the program with new and delete
    // for no memory leaks with vectors (type safe)
    // however, just calling delete is not enough to free all memory
    // at runtime
    vector <int> * test_vect = new vector <int> (10,5);

    // Print out its size
    cout << "The size of the vector is " << test_vect->size()
         << " elements" << endl;

    // run through vector and display each element within boundary
    for (long i = 0; i < (long)test_vect->size(); ++i){
        cout << "Element " << i << ": " << test_vect->at(i) << endl;
    }

    delete test_vect;
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

但是,使用valgrind后,我得到了内存泄漏

==2301== HEAP SUMMARY:
==2301==     in use at exit: 4,184 bytes in 2 blocks
==2301==   total heap usage: 4 allocs, 2 frees, 4,248 bytes allocated
==2301== 
==2301== LEAK SUMMARY:
==2301==    definitely lost: 0 bytes in 0 blocks
==2301==    indirectly lost: 0 bytes in 0 blocks
==2301==      possibly lost: 0 bytes in 0 blocks
==2301==    still reachable: 4,096 bytes in 1 blocks
==2301==         suppressed: 88 bytes in 1 blocks
Run Code Online (Sandbox Code Playgroud)

如何通过指向vector的指针(即在运行时)摆脱所有内存泄漏的痕迹?

小智 22

对于初学者,我不相信有泄漏.你是否正确阅读了Leak Summary你为该计划发布的内容?:

==2301== LEAK SUMMARY:
==2301==    definitely lost: 0 bytes in 0 blocks
==2301==    indirectly lost: 0 bytes in 0 blocks
==2301==      possibly lost: 0 bytes in 0 blocks
==2301==    still reachable: 4,096 bytes in 1 blocks
==2301==         suppressed: 88 bytes in 1 blocks
Run Code Online (Sandbox Code Playgroud)

您在0个块中丢失了0个字节.valgrind找不到任何确定的,间接的或可能的泄漏.你的程序很好.

旁白: 你......真的不应该使用newdelete在这种情况下使用该向量.C++与C一样,如果将它们声明为常规变量,那么它们就会进入堆栈范围并超出范围.以下代码完全实现了您在问题中所做的操作,而无需使用new和delete:

int main (void){
    // Now let's test the program with new and delete
    // for no memory leaks with vectors (type safe)
    // however, just calling delete is not enough to free all memory
    // at runtime (ThePhD: it is, actually!)
    vector <int>  test_vect(10,5);

    // Print out its size
    cout << "The size of the vector is " << test_vect.size() 
         << " elements" << endl;

    // run through vector and display each element within boundary
    for (long i = 0; i < (long)test_vect.size(); ++i){
        cout << "Element " << i << ": " << test_vect.at(i) << endl;
    }

    // ( ThePhD: Look ma, no deletions! )
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

堆栈将神奇地清理自己,因为std :: vector有一个析构函数,当它超出范围时清理它的资源.您不需要将其设置为动态并将其放在程序存储器的堆/自由存储区域,当堆栈完成它时就可以了.

此外,听起来你来自C,所以我会花时间说:欢迎使用C++.:d

  • <3 @Rapptz让我知道如何真正阅读Valgrind.:d (2认同)

sta*_*ust 6

我认为这可以是答案.就C++而言,这里没有泄漏.