c++ - 当您将文字常量分配给右值引用时会发生什么?

标签 c++ move-semantics

诚然,这是一个挑剔的问题,主要是出于好奇。假设我们有以下内容:

int x = 5;
int&& xref = std::move(x);
std::cout << "Before assignment x: " << x << std::endl;
std::cout << "Before assignment xref: " << xref << std::endl;
xref = 10;
std::cout << "After assignment x: " << x << std::endl;
std::cout << "After assignment xref: " << xref << std::endl;

预期的输出是:

// Before assignment x: 5
// Before assignment xref: 5
// After assignment x: 10
// After assignment xref: 10

这是有道理的。 std::movex 转换为 xvalue 并允许我们将其内存位置绑定(bind)到 xref 并相应地修改其内容。现在假设我们有以下内容:

int&& xref = 5;
std::cout << "Before assignment xref: " << xref << std::endl;
xref = 10;
std::cout << "After assignment xref: " << xref << std::endl;

int x = 5;
std::cout << "After assignment x: " << x << std::endl;

输出很直观:

// Before assignment xref: 5
// After assignment xref: 10
// After assignment x: 5

这在整体上是有道理的。我们希望能够将常量文字 5 绑定(bind)到 xref,因为 5 是纯右值。我们还希望 xref 是可变的。我们进一步期望常量文字 5 的值是不可修改的(如上面代码片段的最后两行中有点迂腐的所示)。

所以我的问题是,这里究竟发生了什么? C++ 如何知道不修改常量文字 5 的值,同时保持足够的身份让 xref 知道它已被更改为 10那作业。当它绑定(bind)到常量文字时,是否在分配给 xref 时创建了一个新变量?这个问题在 C++03 中从未出现过,因为只有 const 引用可以绑定(bind)到右值。

最佳答案

int&& xref = 5;

... 创建一个临时的,初始化为 5,其生命周期延长到 block 的末尾。

作业

xref = 10;

更改仍然活着的临时值。

关于c++ - 当您将文字常量分配给右值引用时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33085796/

相关文章:

c++ - 但是将内存转换为字节数组?

c++ - 对称访客模式

c++ - RVO 和 NRVO 优化 + C++11 move 运算符

c++ - 了解默认 move 构造函数定义

c++ - 为什么在返回兼容类型时需要显式 std::move?

c++ - 在将参数传递给基类时使用 std::move()

c++ - 何时使用递归互斥锁?

c++ - SDL2 无法捕获控制台键盘事件?

C++引用与指针的关系

c++ - 重铸空指针容器