相关疑难解决方法(0)

手动调用析构函数总是一个糟糕的设计标志?

我在想:他们说如果你手动调用析构函数 - 你做错了什么.但情况总是这样吗?有反例吗?有必要手动调用它或者难以避免的情况/不可能/不切实际的情况吗?

c++ destructor coding-style

73
推荐指数
6
解决办法
9万
查看次数

如果构造函数抛出异常会发生什么?

那我们会得到UB吗?我试过这个:

#include <iostream>

struct B
{
    B(){ std::cout << "B()" << std::endl; }
    ~B(){ std::cout << "~B()" << std::endl; }
};

struct A
{
    B b;
    A(){ std::cout << "A()" << std::endl; throw std::exception(); }
    ~A(){ std::cout << "~A()" << std::endl; }
};

int main()
{
    A a;
}
Run Code Online (Sandbox Code Playgroud)

desctructor没有被要求netither A也没有B.实际输出:

B()
A()
terminate called after throwing an instance of 'std::exception'
  what():  std::exception
bash: line 7: 21835 Aborted                 (core dumped) ./a.out
Run Code Online (Sandbox Code Playgroud)

http://coliru.stacked-crooked.com/a/9658b14c73253700

因此,在块范围变量初始化期间构造函数抛出的任何时候,我们都得到UB吗?

c++ initialization

22
推荐指数
2
解决办法
2万
查看次数

标签 统计

c++ ×2

coding-style ×1

destructor ×1

initialization ×1