In this example, is the c-style cast to int&
followed by an assignment to kind of hack the interface of class A
undefined behavior?
class A
{
public:
A()
: x(0)
{
}
~A()
{
std::cout << x << std::endl;
}
const int& getX()
{
return x;
}
private:
int x;
};
int main()
{
A a;
int& x = (int&)a.getX();
x = 17;
std::cout << x << std::endl;
}
Output:
17
17
If so, what part of the standard can i refer to? Also, is there any reason why this compiles without warnings? (i tested with c++14 on cpp.sh with -Wall, -Wextra and -Wpedantic)
const int& getX() { return x; }
Since this method is not marked const, x is a mutable int. A reference is taken and cast to a const int& at the point of return. Note that although the reference is to a const int, the actual referee int is mutable. This is important.
int& x = (int&)a.getX();
This line takes the returned const int reference and const_cast
's it to an int reference. This is legal in c++, full stop. [expr.const.cast]
However, writing through this reference is only legal if the original object being referenced is mutable.
In this case, it is.
You will find the details in [dcl.type.cv]