std :: vector.clear()是否删除(可用内存)每个元素? [英] Does std::vector.clear() do delete (free memory) on each element?

查看:964
本文介绍了std :: vector.clear()是否删除(可用内存)每个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

#include <vector>

void Example()
{
    std::vector<TCHAR*> list;
    TCHAR* pLine = new TCHAR[20];
    list.push_back(pLine);
    list.clear();    // is delete called here?
    // is delete pLine; necessary?
}


$ b <也就是说我需要释放内存之前/之后的list.clear()?

Does list.clear() call delete on each element? I.e. do I have to free the memory before / after list.clear()?

推荐答案

在结束,因为你建议在你的例子中,秃头指针的破坏不做任何事情)。但是你可以使用boost [或其他基于RAII的成语]智能指针来做正确的事情( auto_ptr 在容器中不能正常工作,因为它具有不兼容的行为在复制等),但确保你理解这种智能指针的使用前的陷阱。 (正如Benoit提到的,在这种情况下, basic_string 是你真正想要的。)

No (you need to do the delete yourself at the end as you suggest in your example as the destruction of the bald pointer doesnt do anything). But you can use a boost [or other RAII-based idiom] smart pointer to make it Do The Right Thing (auto_ptr would not work correctly in a container as it has incompatible behaviour under copying etc.), but be sure you understand the pitfalls of such smart pointers before use. (As Benoit mentions, in this case, basic_string is what you're really looking for here.)

说,有必要了解智能指针的陷阱,让他们明确地处理内存管理,所以你不必明确地做它是明显更不容易出错。

Having said that there's a need to understand the pitfalls of smart pointers, having them take care of the memory management implicitly so you dont have to do it explicitly is far less error-prone.

编辑:基本上修改为包含元素Benoit带来了更彻底的答案,感谢Earwicker和詹姆斯·马塔的强烈刺激 - 感谢促使我做这方面的尽职调查!

Substantially revised to encompass the elements Benoit brought into his far more thorough answer, thanks to strong prodding from the Earwicker and James Matta - thanks for pushing me to do the due diligence on this!

这篇关于std :: vector.clear()是否删除(可用内存)每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆