rnd_nr_gen
rnd_nr_gen

Reputation: 2281

non-trivial rvalue and lvalue example

I am not sure about some rvalue/lvalue non-trvial examples.

are std::vector<int>({1,2,3})[0] and std::vector<int>() expressions below lvalue or rvalue?

the code has no actual usage but it surprises me a bit that the code is valid. It looks like they are both lvalues. or not?

#include <vector>

int main()
{
    std::vector<int>({1,2,3})[0] = 0;
    std::vector<int>() = {1,2,3}; 
    return 0;
}

further example...

The std::vector<int>() expression below is a rvalue. right? and how about the expression std::vector<int>({1,2,3})[0]?
Both the vector object from std::vector<int>() and the int value from ...[0] are temporary values. right?

auto v = std::vector<int>();
int i = std::vector<int>({1,2,3})[0];

Upvotes: 0

Views: 67

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96276

std::vector<int>() is an rvalue, because the syntax type() always produces an rvalue. std::vector<int>() = {1,2,3}; is allowed because assigning to rvalues of class type is allowed in general, but can be disabled for a specific class by defining operator= with a & qualifier, which std::vector doesn't do.

std::vector<int>({1,2,3})[0] is an lvalue, because std::vector<...>::operator[] is defined to return an lvalue reference. It's possible to define it to return rvalue or lvalue depending on whether the vector it's called on an rvalue or lvalue (see the link above), but std::vector doesn't do that.

Both the vector object from std::vector() and the int value from ...[0] are temporary values. right?

The vector - yes. The int - no, at least formally.

Whether or not something an object is a temporary depends solely on the way it was created, e.g. type() will always give you a temporary.

The vector allocates its elements on the heap, which results in normal, non-temporary objects. It doesn't matter that the vector itself is a temporary.

Upvotes: 0

Related Questions