C++构造函数析构函数中的奇怪行为

Strange behavior in C++ constructordestructor

本文关键字:构造函数 析构函数 C++      更新时间:2023-10-16

我在玩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);

创建临时对象,然后对其进行销毁…