gpt4 book ai didi

c++ - 使用仅使用一次的变量调用的复制构造函数。这可能是通过调用 move 构造函数来优化编译器的情况吗?

转载 作者:行者123 更新时间:2023-11-30 04:55:23 25 4
gpt4 key购买 nike

代码:

#include <iostream>

class A {
public:
A() {
}

A(const A& a) {
std::cout << "Copy constructor" << std::endl;
}

A(A&& a) {
std::cout << "Move constructor" << std::endl;
}
};

int main()
{
{//case 1
A b = A(A());
}
std::cout << std::endl;
{// case 2
A a;
A b = A(a);
}
std::cout << std::endl;
{//case 3
A a;
A b = A(std::move(a));
}
}

输出(带有 -O3 编译标志):

#case 1
#nothing printed

#case 2
Copy constructor

#case 3
Move constructor

在情况 2 中,为什么即使使用最大优化级别 (-O3) 也会调用复制构造函数?我期望编译器检测到变量“a”就像是临时变量(因为仅用于构造“b”),而是使用 move 构造函数(如案例 3)。

据我所知,至少有一种情况(返回值优化),编译器可以通过避免调用具有副作用的复制构造函数来改变程序的可观察行为。
所以我想知道在情况 2 中是否有可能,同样出于优化目的,用 move 构造函数替换复制构造函数的调用,知道变量 a 永远不会在 b 的构造之外使用。

最佳答案

To my knowledge there is at least one case (return value optimization) where the compiler can alter the observable behavior of the program by avoiding the call to a copy constructor which has side effect.

这些情况由标准明确指定,不幸的是,不包括像您的情况 2 这样的情况,因此不允许编译器执行此类改变可观察行为的优化。


标准[class.copy.elision]/3中的相关部分:

In the following copy-initialization contexts, a move operation might be used instead of a copy operation:

  • If the expression in a return statement ([stmt.return]) is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in the body or parameter-declaration-clause of the innermost enclosing function or lambda-expression, or

  • if the operand of a throw-expression 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),

关于c++ - 使用仅使用一次的变量调用的复制构造函数。这可能是通过调用 move 构造函数来优化编译器的情况吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53074046/

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