Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

function - 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 
");
}

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

} 

};
 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...