gpt4 book ai didi

c++ - 下面显示的代码段中没有省略移动构造函数是否有任何特殊原因?

转载 作者:IT老高 更新时间:2023-10-28 22:41:49 27 4
gpt4 key购买 nike

gcc ,clang 和 VS2015 在抛出对象 a 之后,不会在下面的代码中省略对移动构造函数的调用。在我看来,§8.12[class.copy]/31 (N4140) 的要点 (31.2) 中建立的条件已经满足。

#include <iostream>

struct A
{
A() { std::cout << "Default ctor " << '\n'; }
A(const A& a) { std::cout << "Copy ctor" << '\n'; }
A(A&& a) { std::cout << "Move ctor" << '\n'; }
~A() { std::cout << "Destructor " << '\n'; }
};

int main()
{
try
{
A a;
throw a;
}
catch(A& a) { std::cout << "Caught" << '\n'; }
}

注意 a 是一个左值,但根据 §12.8/32,重载决议首先执行为拷贝选择构造函数,就好像对象是由右值指定的一样。也就是说,调用移动构造函数是可以的。如果你删除上面移动构造函数的定义,复制构造函数会被调用,但同样,它不会被忽略!

我知道标准没有强制要求复制省略,但我很想知道是否有任何特殊条件可以证明上述三个编译器在这个特定示例中避免了这种优化这一事实。

gcc 的示例输出,来自上面的链接:

g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out

Default ctor

Move ctor

Destructor

Caught

Destructor

最佳答案

根据 12.8 [class.copy] 第 31 段,第二个项目符号可以省略被抛出的局部变量的拷贝:

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

似乎没有一个编译器使用这种优化。一个原因可能是它根本不值得这样做,因为最好将精力花在其他优化上。我认为标准中没有任何内容禁止这种优化。

关于c++ - 下面显示的代码段中没有省略移动构造函数是否有任何特殊原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32812049/

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