C++构造函数析构函数中的奇怪行为
Strange behavior in C++ constructordestructor
我在玩C++类构造函数,递归地使用它来打印"trauth table"。一切似乎都很正常,直到我决定"为什么不太递归地使用析构函数?"。当我用析构函数实现打印"trauth表"时,我注意到每当控件从递归调用返回构造函数时都会调用析构函数。
输出SNIPET
Calling hello_world class constructor...
000
A destructor call within initialization has been terminated
001
A destructor call within initialization has been terminated
A destructor call within initialization has been terminated
010
...
...
类别
#define MAX 3
class hello_world
{
char *const buf;
int stack_ptr, destructor_calls;
bool init;
public:
// The recursive constructor
hello_world(char *const &str, int i = 0)
: buf(str), stack_ptr(0), init(false), destructor_calls(0)
{
if (i == MAX)
{
buf[i] = ' ';
cout << buf << endl;
}
else
{
buf[i] = '0';
hello_world::hello_world(str, i + 1);
buf[i] = '1';
hello_world::hello_world(str, i + 1);
}
}
// The recusive destructor
~hello_world()
{
++destructor_calls;
if (!init) { cerr << "A destructor call within initialization has been terminated" << endl; return; }
int i = stack_ptr;
if (i == MAX)
{
buf[i] = ' ';
cout << buf << endl;
}
else
{
buf[i] = '0';
++stack_ptr; // since a destructor cannot take parameters
hello_world::~hello_world();
--stack_ptr;
buf[i] = '1';
++stack_ptr;
hello_world::~hello_world();
--stack_ptr;
// Printing total number of calls at final call
if (i == 0) cout << endl << ""destrucotr_calls" = " <<
destructor_calls << endl;
}
}
void unlock()
{
init = true;
}
}; // end of class hello_world
我使用int hello_world::stack_ptr
来存储i
参数的当前数量,因为析构函数不能有参数。
我的问题是:为什么每次控件将递归调用留给构造函数时都调用析构函数。
这是我的main():
void main()
{
char buf[MAX + 1];
cout << "Calling hello_world class constructor..." << endl;
hello_world h(buf);
h.unlock();
cout << "Calling hello_world class destructor..." << endl;
}
我正在使用VS2010。您可以在此处查看完整的代码及其输出。
ADD:我正在尝试计算使用int hello_world::destructor_calls
调用析构函数的总数。我发现打印trauth表算法需要2 * (2^MAX) - 1
调用,最后destructor_calls
正好等于这个值。然而,当计算输出中的句子"A destructor call within initialization has been terminated"
时,我们发现它已经被输出了14次。因此,14(初始化中的调用)+15(打印trauth表的自然调用)应等于29,而destructor_calls
仅等于15(就好像初始化时没有调用析构函数一样!!)
没有递归构造函数这样的东西。看起来像递归的实际上是创建一个新的临时对象。
直接调用析构函数是可能的,但如果在同一对象上调用两次析构函数,则会得到未定义的行为,因此不能递归调用。
您需要做的是在构造函数或析构函数中调用另一个成员函数。然后,您可以使这些其他函数递归:
class A {
A() { construct(); }
~A() { destruct(); }
void construct(int i=0) { ... construct(i+1); ... }
void destruct(int i=MAX) { ... destruct(i-1); ... }
};
你玩火。。。
hello_world::hello_world(str, i + 1);
创建临时对象,然后对其进行销毁…
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- new[] / delete[] 并在C++中抛出构造函数/析构函数
- 创建/向容器添加对象时如何使用构造函数/析构函数
- LNK2019构造函数/析构函数使用 C++ Dll
- 有人可以解释一下这里发生了什么(类和构造函数/析构函数)吗?
- 带智能ptr的Pimpl-为什么需要构造函数/析构函数
- 需要构造函数/析构函数/类型转换错误
- Boost共享指针构造函数/析构函数
- 通过值或引用调用时未调用构造函数/析构函数.不管怎样
- C++构造函数析构函数中的奇怪行为
- 构造函数/析构函数链接错误
- 在模板化函数中调用具有特征的显式构造函数/析构函数
- c++构造函数/析构函数
- 为什么赋值的成本不能保证小于构造函数-析构函数对
- 重写默认构造函数/析构函数而不实现它们
- 使用自定义分配器调用对象构造函数/析构函数
- 涉及类和结构的构造函数/析构函数
- 在抽象构造函数/析构函数中调用纯虚拟函数安全吗
- 如果在没有限定的情况下从构造函数/析构函数调用虚拟函数,则是否会发生虚拟调度
- C++基于堆栈的构造函数/析构函数无法按预期工作