左值,右值的概念是以人的经验习惯为基础的。
根据习惯,等号左边的的值,是被改变的值,是非const的;等号右边的值,是不被改变的,可以是const或非const。
但是在C++里这一切都不是绝对的,比如下面的代码:
C++ 代码:
#include <iostream>
using namespace std;
struct A
{
int x;
A(int k = 0):x(k){}
const A & operator =(A & x) const{
cout<<"operator =()\n";
++x.x;
return *this;
}
};
int main()
{
const A c1(1),c2(2);
A m1(3),m2(4);
c1 = m2; //operator =()
cout<<c1.x<<endl //1
<<c2.x<<endl //2
<<m1.x<<endl //3
<<m2.x<<endl; //5
}
左值是const A,右值却需要是非const的,一切都看编码者怎么设计。