Does std::vector.clear() do delete (free memory) on each element?

后端 未结 6 669
梦谈多话
梦谈多话 2020-12-04 08:14

Consider this code:

#include 

void Example()
{
    std::vector list;
    TCHAR* pLine = new TCHAR[20];
    list.push_back(pLine)         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 08:48

    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.

    EDIT: 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!

提交回复
热议问题