简体   繁体   English

如何为const std :: vector释放内存<unsigned char>

[英]How to deallocate memory for const std::vector<unsigned char>

I am using one library api which returns const std::vector . 我正在使用一个库api,它返回const std :: vector。 Below is the code 下面是代码

const std::vector<unsigned char> myvar = getData();

Now i have cleanup memory for myvar. 现在我有myvar的清理记忆。 How to do this with c++. 如何用c ++做到这一点。

I am trying something like 我正在尝试类似的东西

std::for_each(myvar.begin(), myvar.end(), [&](unsigned char mychar)
{
    cout<<mychar<<",";


    delete &mychar;

});

But failing with the heap curruption. 但失败了堆破坏。

Thanks for the input. 感谢您的投入。

STL uses RAII idiom, , it allocates memory when necessary and deallocate automatically. STL使用RAII惯用语,它在必要时分配内存并自动解除分配。

You don't need to manually deallcoate myvar , just let myvar go out of scope, all memory will be deallocate automatically. 你不需要手动释放myvar ,只是让myvar超出范围,所有内存都将自动解除分配。

// new scope, maybe function, maybe if/while scope: 
{
    const std::vector<unsigned char> myvar = getData();
}
// myvar will be deallocated 

Note, always call new/delete , new [] / delete[] in pair, you didn't call new for any myvar member, you don't need call delete at all. 注意,总是调用new/deletenew [] / delete[]对,你没有为任何myvar成员调用new,你根本不需要调用delete

You do not have to manually delete the contents of that vector. 您不必手动删除该向量的内容。 The vector's destructor will take care of all necessary memory allocation, and will be called when the object goes out of scope. 向量的析构函数将处理所有必要的内存分配,并在对象超出范围时调用。 For example, 例如,

{

  const std::vector<unsigned char> v('a', 1000); // size 1000 vector

} // v's destructor called here.

This is one of the many reasons to use standard library types. 这是使用标准库类型的众多原因之一。 Have a look at the not very aptly named resource acquisition is initialization, or RAII . 看看不是很恰当的命名资源获取是初始化,还是RAII

void myFunc()
{
    const std::vector<unsigned char> myvar = getData();

} // <----- Like this

Vector will take care of deallocating its own contents, when it is destroyed at the end of its containing scope. 当它在包含范围的末尾被销毁时,Vector将负责释放它自己的内容。 Remember, you don't need to delete , unless you new . 请记住,除非你是new ,否则你不需要delete

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

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