4

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.

vladinkoc
  • 919
  • 1
  • 8
  • 13

5 Answers5

10

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

pv = const_cast<string*>(ps);
john
  • 7,897
  • 29
  • 27
4

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.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
3

You have first to remove the const-ness and then to static_cast:

pv = static_cast<void*>(const_cast<string*>(ps));
Francesco
  • 3,200
  • 1
  • 34
  • 46
2

All you need is a const_cast, since conversions to (but not from) void* happen automatically (to convert from void, use static_cast):

pv = const_cast<string*>(ps);
PlasmaHH
  • 15,673
  • 5
  • 44
  • 57
-1

I didn't try - I guess you 2 casts - this should not be used because of the link posted below.

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

the only safe way according to C++03 seems to be to use the static_cast to cast from/to void*

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

I would not use the implicit cast as it hides the cast. But your cast looks like a bad idea - what is the context of this?


I just found when to use reinterpret_cast and now I see why the static_cast is better. Still I don't like it because it somewhat hides (in my opinion) the dangerous part of casting to void. In a review it is easy to simply search for all reinterpret_casts and review the potential dangerous places.

Community
  • 1
  • 1
Tobias Langner
  • 10,634
  • 6
  • 46
  • 76
  • 2
    The reinterpret cast is not necessary, and potentially dangerous. Pointers automatically convert to void pointers, so only the const is needed. – PlasmaHH Oct 23 '12 at 10:16