c++ - 跳过声明时,为什么需要琐碎的析构函数?

标签 c++ destructor goto

gotoswitch 可以跳过声明语句,因为它没有初始化程序并且构造很简单——而且对象也很容易可破坏

对析构函数进行约束的基本原理是什么?

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++ - 跳过声明时,为什么需要琐碎的析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39806710/

相关文章:

c++ - GNU 调试器不显示 C++ 结构中的所有数据

c++ - g++ 部分链接而不是存档?

c++ - 作为 OuterClass 对象成员的 InnerClass 对象被创建了两次

php - PHP如何在脚本关闭时使用对象析构函数中的trigger_error触发用户错误?

python - 如何根据参数值 "skip"多功能 python 脚本中的各个函数

c++ - 将 goto 标签暴露给符号表

c++ - 有没有办法让空的 boost 循环缓冲区的前端在缓存中保持热?

C++ 自动舍入

python - __del__ 的用例

Delphi:在这种情况下 Goto 不被认为是有害的吗?