When int i = 5;
int j = i;
Will rvalue i
in this expression be a constant when evaluating the result?
I'm asking this question because in my copy constructor its argument requires a co开发者_StackOverflow社区nst
There is a common misunderstanding around the lvalue/rvalue terms. They do not refer to variables, but rather to expressions. An expression can yield either an lvalue or an rvalue, and that can be either const or non-const.
In particular, in your code the expression i
on the right hand side of the definition int j = i;
is an lvalue expression, not an rvalue. For the purpose of assignment there is an lvalue to rvalue conversion and then that is assigned to the newly declared variable.
Cont-ness is an orthogonal concept --in most cases-- and relates to whether you can or cannot mutate the object that you are dealing with.
int f();
int& g();
const int& h();
const int k();
int main() {
f(); // non-const rvalue expression
g(); // non-const lvalue expression
h(); // const lvalue expression
k(); // const rvalue expression
f() = 5; // error, cannot assign to an rvalue
g() = 5; // correct, can modify a non-const lvalue
h() = 5; // error, cannot modify a constant lvalue
}
Other examples require the use of user defined types:
struct test {
void foo() { x = 5; }
void bar() const;
int x;
};
test f();
const test g();
int main() {
f().foo(); // f() is a non-const rvalue,
// but you can call a method on the resulting object
g().foo(); // g() is a const rvalue,
// you cannot call a mutating member function
g().bar(); // but you can call a const member function
}
In C++, rvalues of built-in type cannot be const or non-const. It just doesn't make sense. There can be, however, const and non-const rvalues of class types.
An rvalue is just the VALUE (not the object/variable). What would you understand with "non-constant value" ?!
精彩评论