是否删除[]调用析构函数? [英] Does delete[] call destructors?

查看:143
本文介绍了是否删除[]调用析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个模板类,它在内部管理给定类型的数组。像这样:

 模板< typename T& 
class Example {
// ...
private:
T * objects; // allocate in c'tor(array),deleted in d'tor
// ...
};

我想知道C ++是否调用 objects 当我通过 delete []对象; 删除它。



我需要知道这一点,因为我的类中的对象始终不包含合理的值,所以析构函数不应该在没有时调用。



此外,我想知道如果我声明一个固定大小的数组像 T objects [100] 作为示例< T>

解决方案

如果 T 有析构函数将由 delete [] 调用。从 部分的c ++ 11标准(草案n3337),第6节:


如果delete-expression的操作数的值不是空指针值, delete-expression将
调用对象或要删除的数组的元素的析构函数(如果有)强>。在
数组的情况下,元素将按照地址递减的顺序被销毁(即,按照它们的构造函数的完成
的相反顺序;见12.6.2)。


对于 T 类型的析构函数,









$ b


我需要知道这一点,因为我的类中的对象始终不包含合理的值,所以析构函数不应该被调用。 / p>

但是,似乎有一个非常重要的问题,一个对象可以获得一个状态,被破坏。


I am writing a template class which internally manages an array of the given type. Like this:

template<typename T>
class Example {
    // ...
private:
    T* objects; // allocated in c'tor (array), deleted in d'tor
    // ...
};

I was wondering if C++ calls the destructor of each object in objects when I delete it via delete[] objects;.

I need to know this, because the objects in my class do not contain sensible values all the time, so the destructors should not be called when they don't.

Additionally, I'd like to know if the destructors would be called if I declared a fixed-sized array like T objects[100] as part of Example<T>.

解决方案

If T has a destructor then it will be invoked by delete[]. From section 5.3.5 Delete of the c++11 standard (draft n3337), clause 6:

If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).

The destructor for a type T will also be invoked for each element in an array of T[] when the array is not dynamically allocated and array goes out of scope (lifetime ends).


I need to know this, because the objects in my class do not contain sensible values all the time, so the destructors should not be called when they don't.

But, there seems to be a very significant problem with an object that can acquire a state where it cannot be destructed.

这篇关于是否删除[]调用析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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