删除包含C ++ STL中的向量的动态分配的对象 [英] deleting dynamically allocated object that contains vector in C++ STL

查看:75
本文介绍了删除包含C ++ STL中的向量的动态分配的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类

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
};

其中Point是一个结构

where Point is a structure

struct Point{
    CString x;
    double y;    
};

main的 ChartLine new 运算符。
如果我之后使用 delete ,将默认析构函数〜ChartLine()正确dealocate ChartLine :: line (这是向量btw)或者我必须清除〜ChartLine()

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?

提前感谢。
Cheers。

Thanks in advance. Cheers.

推荐答案

隐式创建的析构函数将调用所有成员的析构函数在类中声明。)向量将清除自身。你不需要自己定义析构函数。

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.

这就是为什么你应该更喜欢与RAII结合的自动分配。当对象清理自己,你的代码更安全和更容易。提示:不要使用新的和删除,把它放在一个聪明的指针!

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

这篇关于删除包含C ++ STL中的向量的动态分配的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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