Thread: C++ Faq-lite (Pointer/Reference casts are evil? No.)

  1. #1

    C++ Faq-lite (Pointer/Reference casts are evil? No.)

    Perusing through the C++ Faq-lite, searching for the page to describe a problem to a friend, I come across some references to pointer casting being "evil". First off, I think this is one of the most comprehensive and well written faqs on the web, but I'm going to have to go ahead and really seriously disagree with this one point.

    http://www.parashift.com/c++-faq-lit...html#faq-27.10

    He argues the evilness of other things such as arrays and #defines. I'm inclined to agree on the #defines, and moderatly to a few of his points on arrays. But this casting of types to new types being a problem is simply ridiculous.

    The concept of a feature of C++ being potentially "dangerous" is in no way an argument against it, IMHO. Perhaps one could suggest that container classes are easier than arrays, and type casting should be avoided, when talking to someone _very_ new to C++. But personally I would recomend the practice in using them. How else will one learn? These concepts are intrinsic to the language, and their understanding imparts more than simply the ability to use them.

    I mean, pointer casting (especially to void and back) is rather essential. In some instances I can think of no other way to accomplish certain tasks... And its just plain easier and faster for others. Are we stupid or something? Nobodys going to cast 'foo*' to 'bar*' unless they're both derived from type 'gibble'. And if you do, you're an idiot, and its not the fault of the feature you're using. Theres a million ways to seriously fsk up your app. Why single out this one, simply because its easy to do?

    If I say

    int i;
    delete i;

    Is it the fault of the delete operator, or am I just plain stupid? ... Exactly.

    P.S. Yes, I'm aware that I finally post after months of almost straight silence, and its this irrelevant piece of drivel... What can I say?
    "There's always another way"
    -lightatdawn (lightatdawn.cprogramming.com)

  2. #2
    Registered User
    Join Date
    Sep 2002
    Posts
    272
    >I mean, pointer casting (especially to void and back) is rather essential. In some instances I can think of no other way to accomplish certain tasks... <

    What tasks?

    edit -

    >If I say

    int i;
    delete i;

    Is it the fault of the delete operator, or am I just plain stupid? ... Exactly. <

    You'd be stupid, but it is illegal C++ so your stupidity will be caught by the compiler. No problem.
    Last edited by JoeSixpack; 03-19-2003 at 03:57 PM.
    Joe

  3. #3
    Has a Masters in B.S.
    Join Date
    Aug 2001
    Posts
    2,263
    im totally with you on this Light.

    he should try coding in C.

    if i code something like that its because i have or need to. and i know what the hell im doing, just cause you dont doesnt mean its wrong.

    on point 27.3:
    C++ is not just a god damned OOPL it has freaking PP facilities FOR A REASON!!!, just cause i dont always use it as an OOPL doesnt make me wrong. DAMNIT!!!!

    ok i feel better, and im not gonna read any ore of that... i might get an aneurysm, thanks light...
    ADVISORY: This users posts are rated CP-MA, for Mature Audiences only.

  4. #4
    Registered User
    Join Date
    Sep 2002
    Posts
    272
    >if i code something like that its because i have or need to. and i know what the hell im doing, just cause you dont doesnt mean its wrong.<

    ...and the point of coding standards goes straight over no-ones head.
    Joe

  5. #5
    Has a Masters in B.S.
    Join Date
    Aug 2001
    Posts
    2,263
    >...and the point of coding standards goes straight over no-ones head.

    no no no, you miss my point, codng standards should never limit the functionality of a language, especially just because someone can't follow ereet C style masterpieces.


    ::edit::

    also they should not be used as a judge of a programmers know how or skill just because he dont not follow ever one all the time, some times you have to do what you have to do.
    ADVISORY: This users posts are rated CP-MA, for Mature Audiences only.

  6. #6
    Registered User
    Join Date
    Sep 2002
    Posts
    272
    >no no no, you miss my point, codng standards should never limit the functionality of a language<

    I think C++ would be a mess if you didn't 'limit' its functionality in a team situation. I'm not entirely sure to the extent you're limiting it's basic functionality by imposing a certain paradigm, anyway.

    >also they should not be used as a judge of a programmers know how or skill just because he dont not follow ever one all the time, some times you have to do what you have to do.<

    Are you sure you're not reading something into this? The faq states -

    If coding standards have merit, it is that they discourage the petty fragmentation that occurs when large organizations coordinate the activities of diverse groups of programmers.
    Joe

  7. #7
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078

    Re: C++ Faq-lite (Pointer/Reference casts are evil? No.)

    Concerning c++ (NOT c), in very rare cases pointer casting might be found useful, but most often, it's a quick solution for a design flaw. In an OOP C++ program, specifically void pointer casting should never have to be used (and yes, this is one of the few times that I actually will say never).

    Originally posted by lightatdawn
    I mean, pointer casting (especially to void and back) is rather essential. In some instances I can think of no other way to accomplish certain tasks...
    If you find yourself "having to do so" then you are probably missing a relationship between the types you are casting between (inheritance). Of course, this is assuming that you are using oop, which isn't necissarily true. If you are not an oop programmer, then your use of casting is more understandable.

    But if your programs truely are OOP and "properly" designed (yeah, I know, I don't like saying that word either), I can't think of very many times you'd have to pointer cast between types. The only situtations I can think of are things such as binary fileio, or enumerating a child type from a list and casting it such that you can access all of its information (and even here the datatypes are related via inheritance). There are probably more times, but these are what I can think of off the top of my head. Pointer casting is not an elegant solution, but should generally be looked at as a "quick fix" for a design flaw. Again, it may not always be a design flaw, but if you find youself having to do it often, then you should think twice about it because it probably is.

  8. #8
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    I agree; it should never have to be used in new systems. However, interfacing with systems designed and originally implemented 10-15 years ago is a different story. (Try programming in Win32, casting is unavoidable) Sometimes in bridging the gap between between our system and another we can't avoid pointer-casting or many other constructs deemed evil.

  9. #9
    >>You'd be stupid, but it is illegal C++ so your stupidity will be caught by the compiler. No problem.

    True. But how about:

    int i;
    int *p = &i;

    delete p;

    >>Of course, this is assuming that you are using oop

    Yes, I program purely OO.

    >>What tasks?

    I probably brought thus on myself by saying essential. Note my sig to know that I'm the first to say theres always several solutions. I'll try to give some examples but I'm not on my computer and I type really slow on this Dvorak keypad.

    My most common useage is, as you already noted, binary file io.

    Something like:

    HRESULT _SafeIO::SafeWrite(void * pEntry, size_t ByteSize, ...)

    >>Pointer casting is not an elegant solution

    Not in most situations, no, but that doest mean it should be tarred and feathered. An Impact Screwdriver is a very useful tool (for removing rusted/stuck screws). If I used it to tighten my sunglasses arms, that would make me super stupid, and in no way reflect on the potential usefulness of the tool used with care.

    And this doesnt even bring into account that the faq actually refers to both pointer and reference casting. How many people can honestly refute the use of that?

    Everything in C++ is potentially lethal. Knowledge and care allow us to weild it with relative *cough* safety. We're all aware that certain practices are more prone to error than others. I wouldn't recommend pointers in any form to someone who started programming only a day earlier. That doesnt make them wrong, just not recommended for the skill level of some.
    "There's always another way"
    -lightatdawn (lightatdawn.cprogramming.com)

  10. #10
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    Im completely with poly on this one. Only real exceptions are when programming for windows as has already been noted.

    light, shouldnt that safewrite func be a template taking typed parameters not void?
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  11. #11
    >>light, shouldnt that safewrite func be a template taking typed parameters not void?

    It passes the values straight to fwrite (after various tests and checks). I see no reason to pass typed parameters when fwrite wants a void * anyway. Why bloat my app with unnecessary templating?

    >>Im completely with poly on this one.

    I agree with poly too. But as you both noted, there are in fact legitimate uses, however rare. That being the case, I dont see it fair to put it to the torch on a respected website, for the extremly impressionable newbie to take to heart. To fully understand all aspects of the language is extremly important in creating the most functional code for a given application (IMO).

    And I still fail to see the problem with reference casting...
    "There's always another way"
    -lightatdawn (lightatdawn.cprogramming.com)

  12. #12
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708

    Angry

    Pointer casting WAS invented with the idea of type-safety. References were added for even more safety. IMHO we should have the option to turn off casting enforcement altogether.

    What I hate is C++ casts, they're so long and verbose. I much prefer a C style cast any day.

    And what's wrong with the void* pointer? Have you been reading those crappy OOP articles again?? At least they can't be deleted you fink!
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  13. #13
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    Originally posted by Sebastiani
    Pointer casting WAS invented with the idea of type-safety. References were added for even more safety. IMHO we should have the option to turn off casting enforcement altogether.

    What I hate is C++ casts, they're so long and verbose. I much prefer a C style cast any day.

    And what's wrong with the void* pointer? Have you been reading those crappy OOP articles again?? At least they can't be deleted you fink!
    ummmm, i hope you were joking right there

  14. #14
    Registered User
    Join Date
    Sep 2002
    Posts
    272
    >Why bloat my app with unnecessary templating?<

    There shouldn't be any bloat with a simple templated wrapper function. Doing a quick test on VC++.net appeared to support this, as there was no difference between the release binary sizes for a quick test using templated and non-templated wrappers.

    In any case, all this is completely irrelevant anyway, because your example is invalid. You don't need to cast pointers when passing them into a function with a void* parameter, or assigning a pointer to void; just the other way around.

    Any more tasks?
    Joe

  15. #15
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Sure there's more bloat. But you don't notice it because there are set sizes for most executables, lot's of padding. Take for instance 'hello world!' in assembler would cost a few hundred bytes max, on modern compilers, 64K and up. Inspect one and you'll notice a lot of zeroes.
    If a template is large and many different class and POD types instantiate one, a copy is produced for each version. If 100 templates are available and used the exe will grow quite a bit in real data...I have yet to test that myself,
    tho. ;-/
    Is it neglible? Probably. Memory is so cheap - what's a thousand bytes, ten-thousand? Cheap as lint.
    Anyway, Poly, Stoner, you're both wrong - casting is not evil
    (...programmers are...), in fact there's way too much type-safety anyway. If I had it my way, I would have the option to turn off such measures. It's like the seat-belt laws instituted back in the '80's [ do you know how many red-necks that ........ed off here? ] Who's business is it anyway? At least you can still buy an old car unequipped with seatbelts!
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Wiki FAQ
    By dwks in forum A Brief History of Cprogramming.com
    Replies: 192
    Last Post: 04-29-2008, 01:17 PM
  2. Resident Evil: The Evil Begins-Coder Needed
    By ^Tomala^ in forum Projects and Job Recruitment
    Replies: 8
    Last Post: 01-04-2005, 05:37 PM
  3. FAQ Check/Lock
    By RoD in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 10-15-2002, 11:21 AM