Is const_cast<const Type*> ever useful?

谁说胖子不能爱 提交于 2019-12-04 01:43:44

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.

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.

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*);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!