POV-Ray : Newsgroups : povray.off-topic : Computer language quirks : Re: Computer language quirks Server Time
30 Jul 2024 02:19:20 EDT (-0400)
  Re: Computer language quirks  
From: Warp
Date: 15 May 2011 04:00:04
Message: <4dcf8804@news.povray.org>
Darren New <dne### [at] sanrrcom> wrote:
> On 5/14/2011 0:40, Warp wrote:
> >    For example, in C the only way to make an explicit cast is using the
> > syntax "(type) variable". However, C++ added the possibility of writing
> > such casts as "type(variable)". This allows for 'type' to not only be a
> > basic type, but also a class (in which case it would be a constructor
> > call).

> That's cool. I'm still not sure whether to like C++ or hate it. ;-)

> So what's the static_cast<...> bit all about, then? Is that just something 
> easy to grep for, or does it have different semantics than a regular cast?

  The C-style cast will cast from anything to anything else. Hence it's
not the safest thing in the world, as it's relatively easy to miscast and
have your program misbehave.

  static_cast will only work between compatible types. For example you can
cast an int to a char, a signed int to an unsigned int, classes to other
classes within their inheritance hierarchy, and so on. However, if you try
to static_cast between incompatible types, you will get a compiler error.
For example, you can't cast an int to a pointer, a const pointer to a
non-const one (even if the pointers are of the same type) or between classes
not in direct inheritance relationship.

  It is thus recommended to use static_cast instead of C style casts
whenever possible. Incidentally (but not surprisingly), if you use
static_cast to cast some variable to a class type, and that class has
a constructor that takes a value of that type, it will work. (It will
be the same as constructing the object with the regular syntax.) Supporting
the C style of casting exists more or less just for compatibility with C
code (which of course means that many C++ programmers are using it instead
of static_cast because it's shorter and more "convenient").

  To cast constness away between compatible types const_cast should be
used. (It's basically its only role.)

  To cast between incompatible types reinterpret_cast should be used.
(It assumes you know what you are doing.)

  reinterpret_cast should *not* be used to cast between pointers to objects
in the same inheritance hierarchy because it may forgo adjusting the pointer
offset which may be necessary in some situations.

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.