POV-Ray : Newsgroups : povray.off-topic : Computer language quirks : Re: Computer language quirks Server Time
30 Jul 2024 02:28:53 EDT (-0400)
  Re: Computer language quirks  
From: clipka
Date: 15 May 2011 04:36:26
Message: <4dcf908a$1@news.povray.org>
Am 14.05.2011 18:34, schrieb Darren New:
> 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?

"5.2.9 Static cast [expr.static.cast]
1  The result of the expression static_cast<T>(v) is the result of 
converting the expression v to type T. If T is a
reference type, the result is an lvalue; otherwise, the result is an 
rvalue. Types shall not be defined in a static_cast.
THE STATIC_CAST OPERATOR SHALL NOT CAST AWAY CONSTNESS (5.2.11)."
(emphasis added)

I.e. the static_cast of a const pointer remains a const pointer. It is 
therefore a good idea to always use static_cast instead of a classic 
cast, as it prevents accidental "stripping" of the const property; 
consider, for instance, the following code:

     void foo(int* x);
     void bar(void* x) {
         ...
         foo((int*)x);
         ...
     }

Now assume the code is refactored to use const qualifiers, but for some 
reason the cast in the call to foo() goes unnoticed:

     void foo(const int* x);
     void bar(const void* x) {
         ...
         foo((int*)x);
         ...
     }

Now assume a functionality change requires foo() to modify its parameter:

     void foo(int* x);
     void bar(const void* x) {
         ...
         foo((int*)x);
         ...
     }

The code still compiles, so it goes unnoticed that the function 
signature of bar() is now actually wrong.

If the original code author had used static_cast instead, the mistake 
would have been detected by the compiler, as the following code raises 
an error due to mismatching const qualifiers:

     void foo(int* x);
     void bar(const void* x) {
         ...
         foo(static_cast<int*>x);
         ...
     }


Post a reply to this message

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