10

Let say I have the following code

int main(){
    new int; // Is this expression l-value or r-value??

    return 0;

}

I know that lvalues are persistent object (since it has specific place in memory from where we can access latter even after the expression ends) and rvalues are temporary object (it has no place in memory and vaporizes after the expression ends).

I saw some where that it is rvalue expression. How can it be rvalue if the expression returns an address ( a specific place in memory). Or Is it rvalue because what ever the expression new int returns (an address value), it vanishes and could never be caught after the expression ends.

1 Answer 1

14

new int is an r-value.

You can't use:

int i;
(new int) = &i;

Perhaps you are thinking of the object whose address is returned by new int. The expression denoting the object whose address is returned, *(new int), is an l-value. You can use:

*(new int) = 10;

That's not good code. It leaks memory, but it is legal code.

11
  • 5
    If I understand it correctly, it is an r-value before C++11, and a pr-value after C++11, right?
    – Rakete1111
    Commented Aug 8, 2016 at 5:01
  • 1
    @Rakete1111, yes it is a prvalue starting from C++11.
    – R Sahu
    Commented Aug 8, 2016 at 5:08
  • 1
    @Rakete1111 prvalues are a subset of rvalues, so you could say it was an rvalue in all versions.
    – M.M
    Commented Aug 8, 2016 at 5:09
  • 2
    @pokche, *x is not any sort of conversion of x, it's a dereference. You may be thinking of the conversion done in something like int *x = new int; - while new int itself may be render an rvalue, x is an lvalue (or some variant thereof).
    – paxdiablo
    Commented Aug 8, 2016 at 5:17
  • 6
    "The object whose address is returned is an l-value." Objects don't have value categories. Expressions have value categories.
    – T.C.
    Commented Aug 8, 2016 at 7:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.