简体   繁体   English

在 C++ 中删除指针向量的正确方法

[英]Correct way to delete a vector of pointers in C++

Given the next snipped:鉴于下一个剪断:

vector<cv::Mat> list; // Hold the pointer values (not the pointers)

for (int index = 0; index < item_count; index++)
{
    jobject bitmap = env->GetObjectArrayElement(listBitmaps, index);

    // BitmapUtils::toMat returns a cv::Mat* which has been created with "new cv::Mat()"
    cv::Mat* mat = BitmapUtils::toMat(bitmap);

    list.push_back(*mat); // Store the object value
}

Is next the correct way to delete the vector object pointers?接下来是删除向量 object 指针的正确方法吗?

for (auto entry : sources)
{
    delete & entry;
}

Note that I can't use a vector of pointers such as vector<cv::Mat *> .请注意,我不能使用诸如vector<cv::Mat *>之类的指针向量。

When a Vector instance is reaching its end of scope (end of life) then the destructor of all its containing objects are called.当 Vector 实例到达其 scope 的末尾(生命周期结束)时,将调用其所有包含对象的析构函数。 So if you have objects in a vector (not pointers to objects) then you don't need to do any explicit call of deletes, not counting the one in that your object's destructor.因此,如果您在向量中有对象(不是指向对象的指针),那么您不需要对删除进行任何显式调用,而不是将对象的析构函数中的那个计算在内。

In contrast, if you have pointers in a vector, you need to call delete on those pointers, if you want to release their associated objects, making sure they're still pointing to existing objects (ie not deleted already by some other part of code).相反,如果向量中有指针,则需要对这些指针调用 delete,如果要释放它们的关联对象,请确保它们仍指向现有对象(即尚未被代码的其他部分删除)。

Finally, to make sure you don't have memory leaks, it's always a good idea and advised to make a test run of your program with Valgrind.最后,为了确保您没有 memory 泄漏,这始终是一个好主意,并建议使用 Valgrind 对您的程序进行测试运行。

"Is next the correct way to delete the vector object pointers?" “下一步是删除向量 object 指针的正确方法吗?” No, it's not.不,这不对。

If sources has type vector<cv::Mat *> you have to delete the pointers with如果sources的类型为vector<cv::Mat *>你必须delete指针

for (auto entry : sources)
{
    delete entry;
}

The vector vector<cv::Mat> list;向量vector<cv::Mat> list; has automatic storage duration.具有自动存储期限。 It will be automatically destroyed at the end of its block.它将在其块结束时自动销毁。 It will allocate and deallocate the memory for its elements.它将为其元素分配和释放 memory。 You are not allowed to delete the vector or its elements.不允许delete向量或其元素。

If you have to delete the pointer returned by cv::Mat* mat = BitmapUtils::toMat(bitmap);如果必须delete cv::Mat* mat = BitmapUtils::toMat(bitmap);返回的指针you could do it this way:你可以这样做:

vector<cv::Mat> list; // Hold the pointer values

for (int index = 0; index < item_count; index++)
{
    jobject bitmap = env->GetObjectArrayElement(listBitmaps, index);

    // BitmapUtils::toMat returns a cv::Mat* which has been created with "new cv::Mat()"
    cv::Mat* mat = BitmapUtils::toMat(bitmap);

    list.push_back(*mat); // Store the object value
    delete mat;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM