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/51985202/

相关文章:

c++ - QWidget 不显示 QLabel

c++ - sem_timedwait 与 CLOCK_MONOTONIC_RAW/CLOCK_MONOTONIC

c++ - Boost Beast Async Websocket Server 如何与 session 交互?

c++ - OpenCV ORB GPU 实现比 CPU 慢

c++ - move 语义和原始类型

c++ - 为什么复制和 move 构造函数以相同数量的 memcopies 结束?

c++ - 对 std::move(x) 执行一些操作

C++:如何在不向 shell 传递命令的情况下执行文件?

c++ - vector 元素的 move 分配不起作用,而是调用了“复制分配”

c++ - 为 POD-ish 类型 move 语义