In the following snippet, why does the line o.margin() = m;
compile without fault? It easily deserves a warning, since it will almost invariably be a mistake. I would actually have thought it to be an error since it puts an R-Value on the left side of an assignment.
#include <iostream>
struct Margin
{
Margin(int val=0) : val(val) {};
int val;
};
struct Option
{
Margin m;
int z=0;
Margin margin()const { return m; }
int zoomLevel() { return z; }
};
int main()
{
Option o;
std::cout << "Margin is: "<< o.margin().val << std::endl;
Margin m = { 3 };
// The following line is a no-op, which generates no warning:
o.margin() = m;
// The following line is an error
// GCC 4.9.0: error: lvalue required as left operand of assignment
// clang 3.8: error: expression is not assignable
// MSVC 2015: error C2106: '=': left operand must be l-value
o.zoomLevel() = 2;
std::cout << "Margin is: "<< o.margin().val << std::endl;
return 0;
}
Output:
Margin is: 0
Margin is: 0
See Question&Answers more detail:os