Is const_cast<const Type*> ever useful?

岁酱吖の 提交于 2019-12-21 08:27:05

问题


Recently 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)?


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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*);
}


来源:https://stackoverflow.com/questions/5324256/is-const-castconst-type-ever-useful

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