c++ - 指定临时对象的表达式如何是xvalue表达式?

标签 c++ value-categories xvalue prvalue

来自cppreference ,我试图理解产生 xvalues 的表达式,我最终得到了这个总结:

The following expressions are xvalue expressions:

  • ...
  • any expression that designates a temporary object, after temporary materialization.

Temporary materialization是:

A prvalue of any complete type T can be converted to an xvalue of the same type T. This conversion initializes a temporary object of type T from the prvalue by evaluating the prvalue with the temporary object as its result object, and produces an xvalue denoting the temporary object.

根据我对上面引用的理解,临时物化涉及将纯右值转换为 xvalue 以初始化创建的临时值;这意味着每当纯右值被具体化时,就会出现 xvalue 表达式。所以我发现自己必须了解纯右值何时具体化。然后我检查了 this来自 cppreference:

Temporary materialization occurs in the following situations:

  • 1- when binding a reference to a prvalue;
  • 2- when performing a member access on a class prvalue;
  • 3- when performing an array-to-pointer conversion or subscripting on an array prvalue;
  • 4- when initializing an object of type std::initializer_list from a braced-init-list;
  • 5- when typeid is applied to a prvalue
  • 6- when sizeof is applied to a prvalue
  • 7- when a prvalue appears as a discarded-value expression.

Note that temporary materialization does not occur when initializing an object from a prvalue of the same type (by direct-initialization or copy-initialization): such object is initialized directly from the initializer. This ensures "guaranteed copy elision".

任何人都可以帮我举一些简单的例子,说明 xvalue 表达式如何参与情况 3、4 和 7。

最佳答案

situation 3, 4 and 7.

7(丢弃的表达式)是最简单的:

42; // materialize and discard
std::string{"abc"}; // materialize and discard

3(对数组右值进行处理)需要知道如何制作它们

using arr_t = int[2][3];
int a = arr_t{}[0][0]; // have to materialize to be able to subscript

4(制作一个 std::initializer_list)就是 jar 头上写的

std::initializer_list<std::string>{
  "abc"s,
  "def"s
}; // have to materialize the two strings
   // to place them in the secret array pointed to by the list

关于c++ - 指定临时对象的表达式如何是xvalue表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71095951/

相关文章:

c++ - rust-bindgen 绑定(bind)引发 SIGSEGV

c++ - 链接器无法在库中找到符号

c++ - 返回右值引用和临时物化

c++ - 有没有我可以直接获取地址的右值?

c++ - 在 C++ 中,生成临时类类型的表达式可以归入哪些类别(左值、右值、xvalue 等)?

c++ - 即将超出范围的变量是左值还是 x 值?

c# - 使用 Quantlib 时尝试为仪器定价时出错

c++ - OpenCV 平方差和速度

c++ - 字符串文字左值和右值引用的函数重载