gpt4 book ai didi

c++ - 使用移动时不会发生复制省略

转载 作者:太空狗 更新时间:2023-10-29 23:35:48 25 4
gpt4 key购买 nike

为什么这个例子打印:

#include <iostream>

struct X
{
X() = default;
X(X const&) { std::cout << "copy-constructor\n"; }
X(X&&) { std::cout << "move-constructor\n"; }

X& operator=(X)
{
return *this;
}
};

int main()
{
X x, y;
std::cout << "assign from prvalue calls the ";
x = X{};
std::cout << "\nassign from xvalue calls the ";
x = std::move(y);
}

assign from prvalue calls the
assign from xvalue calls the move-constructor

X{}std::move(y) 都是右值,那么为什么只分配给 X{} 会导致复制省略?

最佳答案

复制省略在第一种情况下有效,因为您正在从一个临时值初始化赋值运算符的参数; temporary 可以省略,直接构造参数。用标准的话来说,省略的标准之一是:

when a temporary class object that has not been bound to a reference would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

在第二种情况下,您不是从临时对象而是从现有对象初始化它。它已经在与目标不同的位置构建,因此无法进行上述优化。

关于c++ - 使用移动时不会发生复制省略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28944047/

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