gpt4 book ai didi

c++ - 什么表达式创建 xvalues?

转载 作者:IT老高 更新时间:2023-10-28 12:57:54 25 4
gpt4 key购买 nike

我正在尝试理解 C++11 的概念。

我所说的标准草案:

An xvalue (an “eXpiring” value) also refers to an object, usually near the end of its lifetime (so that its resources may be moved, for example). An xvalue is the result of certain kinds of expressions involving rvalue references (8.3.2). [ Example: The result of calling a function whose return type is an rvalue reference is an xvalue. —end example ]

好的,那么产生 xvalues 的“某些类型的表达式”到底是什么?这部分规范没有详细列出这些表达式。

我了解左值和纯右值(至少我认为,我了解)。

最佳答案

在§5 (C++11 §5[expr]/6) 的介绍中有一个有用的非规范性注释:

[ Note: An expression is an xvalue if it is:

  • the result of calling a function, whether implicitly or explicitly, whose return type is an rvalue reference to object type,

  • a cast to an rvalue reference to object type,

  • a class member access expression designating a non-static data member of non-reference type in which the object expression is an xvalue, or

  • a .* pointer-to-member expression in which the first operand is an xvalue and the second operand is a pointer to data member.

In general, the effect of this rule is that named rvalue references are treated as lvalues and unnamed rvalue references to objects are treated as xvalues; rvalue references to functions are treated as lvalues whether named or not. —end note ]

搜索 §5 的其余部分,这个列表似乎很详尽。列表后面是一个例子:

struct A {
int m;
};

A&& operator+(A, A);
A&& f();
A a;
A&& ar = static_cast<A&&>(a);

The expressions f(), f().m, static_cast<A&&>(a), and a + a are xvalues. The expression ar is an lvalue.

获取 xvalue 表达式的常用方法有两种:

  • 使用std::move移动一个对象。 std::move执行 static_cast到右值引用类型并返回右值引用。

  • 使用std::forward转发一个右值。 std::forward通常在函数模板中使用,以实现函数参数的完美转发。

    如果提供给函数模板的参数是右值,则参数类型将是右值引用,即左值。在这种情况下,std::forward执行 static_cast为右值引用类型并返回右值引用。

    (注意:如果提供给函数模板的参数是左值,则参数类型将为左值引用,std::forward 将返回左值引用。)

关于c++ - 什么表达式创建 xvalues?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11581903/

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