gpt4 book ai didi

c++ - 为什么抛出局部变量调用 moves 构造函数?

转载 作者:可可西里 更新时间:2023-11-01 17:59:57 25 4
gpt4 key购买 nike

最近,我“玩”了右值以了解它们的行为。大多数结果并没有让我感到惊讶,但后来我看到如果我抛出一个局部变量,就会调用 move 构造函数。

在那之前,我认为 move 语义规则的目的是保证对象只有在编译器可以检测到它不再被使用(如在临时对象中)时才会 move (并变得无效),或者用户 promise 不使用它(如 std::move)。

但是,在下面的代码中,这些条件都不成立,我的变量仍在 move (至少在 g++ 4.7.3 上)。

这是为什么?

#include <iostream>
#include <string>
using namespace std;

int main() {
string s="blabla";
try {
throw s;
}
catch(...) {
cout<<"Exception!\n";
}
cout<<s; //prints nothing
}

最佳答案

C++ 标准说 (15.1.3):

Throwing an exception copy-initializes (8.5, 12.8) a temporary object, called the exception object. The temporary is an lvalue and is used to initialize the variable named in the matching handler (15.3).

这段话可能也与这里(12.8.31)相关:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that objectoccurs at the later of the times when the two objects would have been destroyed without the optimization. This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):

(...)

in a throw-expression, when the operand is the name of a non-volatile automatic object (other than a function or catch-clause parameter) whose scope does not extend beyond the end of the innermost enclosing try-block (if there is one), the copy/move operation from the operand to the exception object (15.1) can be omitted by constructing the automatic object directly into the exception object

在Visual Studio 2012中查看,效果:

Exception!
blabla

这看起来确实像是 GCC 中的一个错误。

关于c++ - 为什么抛出局部变量调用 moves 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46518181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com