简体   繁体   中英

Question about const_cast in c++

all: this is quoted from Effective C++ 3rd editiion

const_cast is typically used to cast away the constness of objects. It is the only C++-style cast that can do this.

My question is can const_cast add constness to a non-const object? Actually i wrote a small programme trying to approve my thought.

class ConstTest
{
 public:

 void test() {
    printf("calling non-const version test const function \n");
}

 void test() const{
    printf("calling const version test const function \n");

} 

};
 int main(int argc,char* argv){
 ConstTest ct;
 const ConstTest cct;
 cct.test();
 const_cast<const ConstTest&>(ct).test();//it is wrong to write this statement without the '&',why

}

Omitting the '&' incurs error below:

error C2440: 'const_cast' : cannot convert from 'ConstTest' to 'const ConstTest'

It shows that const_cast can add constness,but seems like you have to cast to a object reference, what is the magic of this reference ?

You don't need const_cast to add constness:

class C;
C c;
C const& const_c = c;

The other way around needs a const_cast though

const C const_c;
C& c = const_cast<C&>(const_c);

but behavior is undefined if you try to use non-const operations on c .

By the way, if you don't use a reference, a copy of the object is to be made:

C d = const_c; // Copies const_c

const_cast can also be used to add constness.

$5.2.11/3 - "For two pointer types T1 and T2 where

T1 is cv1 , 0 pointer to cv1 , 1 pointer to . . . cv1 ,n − 1 pointer to cv1 ,n T
and
T2 is cv2 , 0 pointer to cv2 , 1 pointer to . . . cv2 ,n − 1 pointer to cv2 ,n T

where T is any object type or the void type and where cv1 ,k and cv2 ,k may be different cv-qualifications, an rvalue of type T1 may be explicitly converted to the type T2 using a const_cast. The result of a pointer const_cast refers to the original object.

Consider:

int *t1 = NULL;  // T = int, cv1, 0 = none
int * const t2 = const_cast<int * const>(t1);   // T = int, cv2, 0 = const

As per the quote above, the above is fine and it adds constness to t

But as Herb Sutter says, it probably is not required explicitly to be done most of the times.

const_cast can only be used to cast to pointers and references. It can't be used to cast to objects. Here's why: if you have a const object you can't make it non-const and vice versa - it's already const, you can't redeclare it. You can only try to access it through a pointer or reference without (or with) const.

const_cast cannot modify the constness of the value. So it returns a const reference to the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM