【发布时间】:2012-04-02 22:51:19
【问题描述】:
我目前正在尝试理解 noexcept(就像几乎所有我避免使用旧的“运行时异常规范”的人一样)。虽然我认为我了解了 noexcept 的基本概念,但我不确定在以下情况下会发生什么:
class sample {
public:
sample() noexcept { }//this doesn't throw
sample(const sample & s) noexcept { }
sample(sample && s) noexcept { }
sample & operator=(const sample & s) noexcept {...}
sample & operator=(sample && s) noexcept { ... }
~sample() noexcept() { }//this should never ever throw
sample operator-() const { return *this * -1; }//assuming that there is a operator*…
sample & operator*=(const sample & s) noexcept { ... }
};
sample operator*(sample s1, const sample & s2) { return s1 *= s2; }//same problem as with operator-…
将 sample::operator- 声明为 noexcept 是否安全? (考虑到它在返回时调用构造函数)
编辑:我更新了代码部分,因为问题的中心部分似乎不清楚......
【问题讨论】:
-
@111111:如果能保证操作是
noexcept,那么声明是没有问题的。在某些情况下,您甚至可能希望通过强异常保证实现其他功能,例如swap。 -
@MFH,如果没有被调用的
operator*的声明,就无法知道它是否安全。 -
@111111:所以他们添加了新版本的异常规范只是再次被忽略?我很难相信他们又犯了同样的错误……
-
@MFH:这个网站上的 C++ 程序员最喜欢把自己的偏见和编码习惯逼到别人的喉咙里。最好忽略它们。
-
@MFH:他们重写了异常规范,唯一合理的用途是:保证你不会抛出。在此过程中,他们更改了语法以接受布尔参数,从而允许基于其他异常规范推理异常规范...