gpt4 book ai didi

c++ - 函数调用返回指向对象的指针是纯右值吗?

转载 作者:行者123 更新时间:2023-12-01 14:11:19 25 4
gpt4 key购买 nike

让我们想象一下这个函数:

C* get(C* c, int offset) {
return c + offset;
}

我想知道对该函数的调用是否被评估为纯右值:

C array_c[3];
C* c2 = get(array_c, 2);

get(array_c, 2) 是纯右值吗?

根据Value categories cppreference 页面:

  • a glvalue (“generalized” lvalue) is an expression whose evaluation determines the identity of an object, bit-field, or function;
  • a prvalue (“pure” rvalue) is an expression whose evaluation either :
    • computes a value that is not associated with an object
    • creates a temporary object and denotes it
  • an xvalue (an “eXpiring” value) is a glvalue that denotes an object or bit-field whose resources can be reused;
  • an lvalue (so-called, historically, because lvalues could appear on the left-hand side of an assignment expression) is a glvalue that is not an xvalue;

在我们的示例中,表达式 get(array_c, 2) 指向一个已经存在的对象,该对象在调用后不会过期。所以我们可以说它是一个左值。此外,我们可以编写 *get(array_c, 2) = C{}; 来为表达式赋值。

但是,有两点让我认为它不是左值。首先在cppreference的同一个页面:

The following expressions are prvalue expressions:

  • a function call or an overloaded operator expression, whose return type is non-reference

在我们的示例中,get 函数返回一个非引用,因此根据这个定义,调用应该被评估为纯右值。

另外,我想知道 get(array_c, 2) 是否确实是一个临时的,使它成为一个纯右值,而 *get(array_c, 2) 是一个左值因为我们可以给它赋值。

你怎么看?函数调用是否被评估为左值、纯右值(或其他)?

最佳答案

get(array_c, 2)*get(array_c, 2) 是两个不同的表达式,具有不同的值类别。

get 本身按值返回指针,则 get(array_c, 2) 被视为右值(prvalue)表达式。您不能像 get(array_c, 2) = nullptr; 那样对其进行赋值,也不能像 &get(array_c, 2) 那样从中获取地址,就像 if get 返回其他类型,例如 int

另一方面,*get(array_c, 2)lvalue expression .正如你所说,你可以对其进行赋值,有效与否,返回的指针有效与否无关紧要。

*p, the built-in indirection expression;


PS:赋值可能在类类型的右值上执行;不是判断左值表达式的绝对条件。

关于c++ - 函数调用返回指向对象的指针是纯右值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62692691/

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