deleting dynamically allocated object that contains vector in C++ STL

前端 未结 4 599
闹比i
闹比i 2021-01-23 22:12

I have a class

class ChartLine{

protected:
        vector line; // points connecting the line
        CString name; //line name for legend                 


        
相关标签:
4条回答
  • 2021-01-23 22:21

    The only time you need to worry about vectors (or other containers) in a destructor is if they contain pointers to objects. Since this isn't true in your case, you should be fine.

    0 讨论(0)
  • 2021-01-23 22:22

    The implicitly created destructor will call the destructor of all the members (in the reverse order they are declared in the class.) The vector will clean up after itself. You don't need to define a destructor yourself.

    This is why you should prefer automatic allocation in combination with RAII. When objects clean themselves, your code as safer and easier. Hint: Don't use new and delete, put it in a smart pointer!

    std::auto_ptr<int> p(new int(5));
    boost::shared_ptr<int> p = boost::make_shared<int>(5);
    

    Both of those will delete automatically, and now you're exception safe as well. (Note, the two above do not do the same thing. There are more types of smart pointers as well.)

    0 讨论(0)
  • 2021-01-23 22:33

    The only time you ever need to call delete is after you've called new. Everything else is handled.

    0 讨论(0)
  • 2021-01-23 22:41

    Yes, when a vector is destroyed, all the objects in the vector are destroyed. From the looks of things, your code should work as-is (though assuming the CString is the MFC one, some older versions of it had some memory leaks...)

    0 讨论(0)
提交回复
热议问题