c++ 当跳过一个声明时,为什么需要微不足道的析构函数?

由于goto或switch可以跳过一个声明语句,因为它没有初始化器,并且构造是微不足道的 – 并且该对象也是微不足道的.

对析构函数的约束有什么理由?

struct trivial {
    trivial() = default;
    ~ trivial() = default;
};

struct semi_trivial {
    semi_trivial() = default;
    ~ semi_trivial() noexcept { do_something(); }
};

void foo() {
    goto good_label;  // OK
    trivial foo;
good_label:

    goto bad_label;   // Error: this goto statement
    semi_trivial bar; // cannot jump over this declaration.
bad_label:

    std::cout << "hi\n";
}
最佳答案
目前的措辞是N2762的结果.本文给出以下理由:

6.7 stmt.dcl:

    Jumping over the definition of an automatic variable will pose the problem of whether the destructor for that variable should be run at the end of the block. Thus, the destructor needs to be trivial, i.e. have no effect. Similarly, the default constructor (the one potentially used to initialize the object) is also required to not do anything, i.e. be trivial. No other requirements are necessary.

我想这个情况要记住的是:

int i = 2;
switch (i) {
  case 1:
    semi_trivial st;
    do_something(st);
    break;
  case 2:
    break; // should st be destructed here?
}

事实上,这不是一个容易回答的问题.在这里称之为析构函数并不是显而易见的事情.没有什么好的方法来告诉它是否应该被调用.这里的st变量只用于case 1语句,如果程序员的析构函数被case 2的break语句调用,即使完全没有使用,也没有被构造,程序员会感到惊讶.

转载注明原文:c++ 当跳过一个声明时,为什么需要微不足道的析构函数? - 代码日志