struct A
{
A() {}
private:
A(const A&); // Explicitly disable the copy constructor.
};
int main()
{
const A a1; // OK.
A a2; // OK.
auto a3 = const_cast<A&>(a1); // Compiler error C2248! ???
}
My C++ compiler is the latest VC++ 2013 preview.
The compiler complains for the last line with error C2248: 'A::A' : cannot access private member declared in class 'A'
Why does const_cast not behave as expected?
Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior. So yes, modifying constant variables is undefined behavior.
const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object. const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.
const_cast is safe only if you're casting a variable that was originally non- const . For example, if you have a function that takes a parameter of a const char * , and you pass in a modifiable char * , it's safe to const_cast that parameter back to a char * and modify it.
auto
, by itself, is never a reference type. So the last line is equivalent to
A a3 = const_cast<A&>(a1);
which attempts to copy a1
using the private constructor.
If you want a reference, you need to specify a reference:
auto & a3 = const_cast<A&>(a1);
Of course, attempting to use this reference to modify a1
will give undefined behaviour, since the object itself is const
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With