Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does const_cast not behave as expected?

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?

like image 760
xmllmx Avatar asked Sep 10 '13 02:09

xmllmx


People also ask

Is const_cast undefined behavior?

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.

What is the point of const_cast?

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.

Is const_cast safe?

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.


1 Answers

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.

like image 76
Mike Seymour Avatar answered Sep 23 '22 09:09

Mike Seymour