converting a char* to a const char*

J

James Kanze

But you can. <g> The prohibition is that "The static_cast operator
shall not cast away constness...". [expr.static.cast]/1.

That's a typo. I meant to say that you can't accidentally
remove const.
 
J

James Kanze

But isn't dynamic_cast the preferred way to do that?

Generally. If you're clearly moving to the base class, it
doesn't matter. Otherwise, however, yes, dynamic_cast is
prefered.
 
J

Juha Nieminen

James said:
Generally. If you're clearly moving to the base class, it
doesn't matter. Otherwise, however, yes, dynamic_cast is
prefered.

Btw, is a dynamic_cast internally optimized into a regular static_cast
by the compiler if it determines that the casting is from a derived type
to a base type and thus runtime casting is not required?
 
J

James Kanze

Btw, is a dynamic_cast internally optimized into a regular
static_cast by the compiler if it determines that the casting
is from a derived type to a base type and thus runtime casting
is not required?

The standard says absolutely nothing about implementation, but
it would be a very poor implementation that did any runtime
lookup when the compiler had all of the information already.
 
N

Noah Roberts

Juha said:
You have got it backwards: const_cast is used to *remove* constness,
not to add it.

It can do either. The more common use is of course removing constness.
However, if you have a const overload of a function and you want to
share common code you might very well cast TO const in the non-const
function.

A better way might be to call a common function, but either works. I'd
consider calling a common function even if it contains the entire const
version of the function because I really, really, really object any time
I see a const_cast in code. It is such a dangerous cast that I simply
will NOT use it if I can avoid it in any way. Obviously I won't do more
dangerous things to avoid it but it's hard to think of one.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top