Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the named cast of old style cast: pv = (void*)ps;

Tags:

c++

Code with old style cast:

const string *ps;  
void *pv;

pv = (void*)ps;

I have try three various named casts:

pv = static_cast<void*>(ps); //  error: invalid static_cast from type ‘const string* {aka const std::basic_string<char>*}’ to type ‘void*’

pv = const_cast<void*>(ps); // error: invalid const_cast from type ‘const string* {aka const std::basic_string<char>*}’ to type ‘void*’

pv = reinterpret_cast<void*>(ps); // error: reinterpret_cast from type ‘const string* {aka const std::basic_string<char>*}’ to type ‘void*’ casts away qualifiers

As you can see. Nothing works.

like image 247
vladinkoc Avatar asked Dec 02 '22 21:12

vladinkoc


2 Answers

You should const_cast, but to the right type. The cast from string* to void* will then happen automatically.

pv = const_cast<string*>(ps);
like image 158
john Avatar answered Dec 19 '22 17:12

john


In this special case, it's simply:

pv = const_cast<string*>( ps );

The conversion from string* to void* is implicit. If you wanted to make it explicit, you'd need a second, separate cast:

pv = static_cast<void*>( const_cast<string*>( ps ) );

or

pv = const_cast<void*>( static_cast<void const*>( ps ) );

I don't think making it explicit is particularly necessary, however; the fact that you're using a void* already says that there will be conversions.

like image 31
James Kanze Avatar answered Dec 19 '22 17:12

James Kanze