开发者

Is const_cast<const Type*> ever useful?

开发者_如何学PythonRecently I found a piece of C++ code that effectively does the following:

char* pointer = ...;
const char* constPointer = const_cast<const char*>( pointer );

Obviously the author thought that const_cast means "add const", but in fact const can be just as well added implicitly:

const char* constPointer = pointer;

Is there any case when I would really have to const_cast to a pointer-to-const (const_cast<const Type*> as in above example)?


Where you have 2 overloads and you want to force the const one to be executed. This is often the case when you call one in terms of the other.

class A
{
public:
   B* get();
   const B* get() const;
};

I have a non-const A but want to run get() const I might cast. In particular I might do this in the implementation of the non-const itself.

B* A::get() 
{
   return const_cast<B*>( const_cast< const A*>(this)->get() );
}

Of course we could do:

B* A::get()
{
    const A* constthis = this; // no need to cast
    return const_cast<B*>(constthis->get());
}

so we did not have to cast but it makes the first solution a one-liner and no need to create a temp variable.


const_cast, despite its name, is not specific to const; it works with cv-qualifiers which effectively comprises both const and volatile.

While adding such a qualifier is allowed transparently, removing any requires a const_cast.

Therefore, in the example you give:

char* p = /**/;
char const* q = const_cast<char const*>(p);

the presence of the const_cast is spurious (I personally think it obscures the syntax).

But you can wish to remove volatile, in which case you'll need it:

char const volatile* p = /**/;
char const* q = const_cast<char const*>(p);

This could appear, for example, in driver code.


Maybe to force overload resolution in cases where you have f(T*) and f(const T*).


You can use static_cast to add const as well. So I don't see any situation where you have to use const_cast to add const. But explicit casting (be it one or another) can sometimes be needed when you want to change the type of the object for example for overload resolution.

E.g.

void f(char*);
void f(const char*);

int main()
{
   char* p = 0;
   f(p); //calls f(char*)
   f(static_cast<const char*>(p)); //calls f(const char*);
   f(const_cast<const char*>(p)); //calls f(const char*);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜