tags:

views:

114

answers:

4

I have a class

class ChartLine{

protected:
        vector<Point> line; // points connecting the line
        CString name; //line name for legend        
        CPen pen; //color, size and style properties of the line
};

where Point is a structure

struct Point{
    CString x;
    double y;    
};

In main() I dynamically allocate objects of type ChartLine with new operator. If I use delete afterwards, will default destructor ~ChartLine() properly dealocate (or clear) member ChartLine::line(which is vector btw) or I would have to clear that vector in ~ChartLine() manually?

Thanks in advance. Cheers.

+5  A: 

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.)

GMan
Although `auto_ptr` won't go into STL-type containers. It was introduced for C++95, deprecated C++0x. Short lifetime.
David Thornley
@GMan: Did you mean to refer to `make_shared()` et al or why the *"don't use `new`"*?
Georg Fritzsche
gf: Eh, I meant don't manage the pointer by hand. Hopefully this is clearer.
GMan
It does. *("Don't use new" still reads strange, but maybe i am just becoming pedantic :)*
Georg Fritzsche
@gf: Heh, I agree. Maybe I'll fix this post up someday. :P
GMan
+2  A: 

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...)

Jerry Coffin
+1  A: 

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.

KeithB
A: 

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

rlbond