在 C++11 和更高版本的标准中,是否保证在从函数按值返回类对象时,(可能会抛出异常)复制构造函数不被调用 - 提供移动构造函数是为这个类定义的?背景:假设
struct X {
X() {}
X(const X&) {/* code that might throw exceptions */}
X(X&&) {/* code that never throws exceptions */}
...
};
和
X my_func(some_type& t)
{
X x;
// code that modifies t and x but never throws exceptions
return x;
}
现在,例如,一个表达式,如
some_other_func(my_func(t));
只要函数 some_other_func(const X&)
不抛出异常,就永远不会抛出异常(也就是说,这能保证吗?)?如果 some_other_func
的签名是 some_other_func(X)
会怎么样?
最佳答案
规则很简单:函数被视为可以抛出异常,除非它被标记为不能抛出异常。在这方面,移动构造函数与任何其他函数一样。手动定义时,除非定义了 noexcept
,否则它被认为是潜在的抛出。
隐式默认函数(即自动提供的复制和移动操作)通常遵循以下逻辑:声明为 noexcept
当且仅当它调用的所有函数都是 noexcept
.
关于C++11:当定义移动构造函数时,按值返回对象不会抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46705976/