gpt4 book ai didi

c++ - 为什么以这种方式使用 move 语义无效?

转载 作者:行者123 更新时间:2023-11-30 01:58:51 26 4
gpt4 key购买 nike

当我遇到这种情况时,我正在追踪一个编译错误:

struct Y        
{
int&& y;
Y(int&& y)
: y(y)
{
}
};

struct ZZ {};
struct Z
{
ZZ&& z;
Z(ZZ&& z)
: z(z)
{
}
};

这些都失败了:

exec.cpp: In constructor ‘Y::Y(int&&)’:
exec.cpp:57:10: error: invalid initialization of reference of type ‘int&&’ from expression of type ‘int’
exec.cpp: In constructor ‘Z::Z(ZZ&&)’:
exec.cpp:67:10: error: invalid initialization of reference of type ‘ZZ&&’ from expression of type ‘ZZ’

但我不确定为什么。这里有什么问题?

我正在使用带有 -std=gnu++0x 选项的 g++4.5.3,但它也会与 -std=c++0x 选项一起出现。

最佳答案

任何有名字的东西都是左值。这意味着构造函数参数 y 是一个左值(类型为 int 的右值引用),因为它有一个名称,“y”。

使用 std::move(y) 将其变回右值。

关于c++ - 为什么以这种方式使用 move 语义无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16750927/

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