Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Pointers or references?

Pointers or references?

Scheduled Pinned Locked Moved The Lounge
jsonhelpquestionlearning
36 Posts 16 Posters 2 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J James Pullicino

    Beleiving that reference always "points" to something is NOT dangerous, coding like this is dangerous: Bar* pBar=NULL; Foo(*pBar); James (2b || !2b)

    M Offline
    M Offline
    Maximilian Hanel
    wrote on last edited by
    #16

    James Pullicino wrote: Beleiving that reference always "points" to something is NOT dangerous, coding like this is dangerous: Yes of course it's dangerous. But if you asume that a caller is smart enough not to write code like that than you could also asume that a caller is smart enough not to pass a NULL pointer. What I want to point out is that you can pass an invalid ref. Nobody prevents you from doing that. In the same way nobody prevents you from passing a NULL pointer. So I don't see there any reasons to asume a ref is valid just because it's a ref whereas you always (hopefully) check for NULL pointers. CU Max

    1 Reply Last reply
    0
    • S Stan Shannon

      Or code like this: CTimbuktoo::Foo( *pToSomethingReallyImportant ) { m_pX = pToSomethingReallyImportant; } CBumPhuckEgypt::AnotherFoo( *pToSomethingReallyImportant ) { m_pX = pToSomethingReallyImportant; } Where m_pX is a public variable in both cases. What a nightmare...

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #17

      Stan Shannon wrote: CBumPhuckEgypt Laughed my fucking arse off at that one. I think the whole function declaration is worthy of signature status. Will have to see if I have the energy to change mine. Michael Martin Australia mmartin@netspace.net.au "Don't belong. Never join. Think for yourself. Peace" - Victor Stone

      S 1 Reply Last reply
      0
      • T Tim Smith

        I learned C++ using that Stroustrup's ideas on references too. And like you, I go back and forth on the passing modified arguments via reference. But most of the time, modified arguments end up being by pointer and non-modified end up with a NICE FAT "const". Tim Smith Descartes Systems Sciences, Inc.

        C Offline
        C Offline
        CodeGuy
        wrote on last edited by
        #18

        I dunno -- I still tend toward readability in my own programs, which I think pointers detract from. I think Stroustrup writes from the perspective of large-scale software design, in which you may have a lot of other people reading and using your interfaces, libraries, etc. If that is the case, you probably want to give people as many clues as possible as to what your functions are doing. For programming-in-the-small, I put the pointers/references in the same arena as Get/Set methods for public member variables. (OO heresy! :) ) I've just have never had a debugging issue arise where the pointers vs. references issue made an impact. CodeGuy The WTL newsgroup: over 1100 members! Be a part of it. http://groups.yahoo.com/group/wtl

        T 1 Reply Last reply
        0
        • J Joaquin M Lopez Munoz

          They're not exactly the same, because references enforce an additional constraint that pointers do not, namely with references you cannot pass a "null" object (typically represented by the null pointer). So my rationale for deciding between the two styles is:

          1. If the parameter can be "void" and this is well represented by the null pointer, use pointers.
          2. In any other case, use references.

          Joaquín M López Muñoz Telefónica, Investigación y Desarrollo

          E Offline
          E Offline
          Eddie Velasquez
          wrote on last edited by
          #19

          You forgot to mention that references cannot be "reseated", that is, you can't change the entity the reference "points" to. Foot-and-Mouth disease is believed to be the first virus unable to spread through Microsoft Outlook

          R 1 Reply Last reply
          0
          • J James Pullicino

            When deciding whether to use pointers or references as function parameters, remember this: When passing by reference, the parameter is garanteed to be a valid (existing) object, when passing by pointer, it is not. Therefore whenever possible pass by reference since: - you'll produce safer code - no validation of the object is required - easier to code (no -> and *x = 10 etc...) - compiler will catch incorrect type casts When it is not possible, pass by pointer and understand the dangers. James (2b || !2b)

            E Offline
            E Offline
            Eddie Velasquez
            wrote on last edited by
            #20

            James Pullicino wrote: the parameter is garanteed to be a valid (existing) object, This is true when everybody is playing by the rules. It is possible to have "null" references and references to invalid objects, but this is an abomination and the person responsible should be put to a slow and painful death. :) Foot-and-Mouth disease is believed to be the first virus unable to spread through Microsoft Outlook

            1 Reply Last reply
            0
            • C CodeGuy

              I dunno -- I still tend toward readability in my own programs, which I think pointers detract from. I think Stroustrup writes from the perspective of large-scale software design, in which you may have a lot of other people reading and using your interfaces, libraries, etc. If that is the case, you probably want to give people as many clues as possible as to what your functions are doing. For programming-in-the-small, I put the pointers/references in the same arena as Get/Set methods for public member variables. (OO heresy! :) ) I've just have never had a debugging issue arise where the pointers vs. references issue made an impact. CodeGuy The WTL newsgroup: over 1100 members! Be a part of it. http://groups.yahoo.com/group/wtl

              T Offline
              T Offline
              Tim Smith
              wrote on last edited by
              #21

              I've just have never had a debugging issue arise where the pointers vs. references issue made an impact. Damn straight!!! Which is why I consider it more a question of style than program reliability. Tim Smith Descartes Systems Sciences, Inc.

              1 Reply Last reply
              0
              • T Thomas Freudenberg

                S. Spenz wrote: I think pointers look much better than this ugly & I do not think that this is a question of aesthetics ;) S. Spenz wrote: Of course sometimes you have no choice but if what would you choose? I really like declarations such as void foo (const bar& x);. This is safe, you cannot even change x accidentally. Regards Thomas Finally with Sonork id: 100.10453 Thömmi


                Disclaimer:
                Because of heavy processing requirements, we are currently using some of your unused brain capacity for backup processing. Please ignore any hallucinations, voices or unusual dreams you may experience. Please avoid concentration-intensive tasks until further notice. Thank you.

                E Offline
                E Offline
                Eddie Velasquez
                wrote on last edited by
                #22

                Thomas Freudenberg wrote: void foo (const bar& x);. I got used to put the modifiers (const, volatile) to the right of the type as I find it easier to read (and understand). I would express your example as

                void foo(bar const& x); // Notice the const after the typename

                I found out that reading declarations from right to left is easier. e.g.

                void foo(char const* p); // 1) Read as "p is a pointer to a constant char"
                void foo(char* const p); // 2) Read as "p is a constant pointer to a char"
                void foo(char* const* p); // 3) Read as "p is a pointer to a constant pointer to a char"

                1. Means that the contents of the object pointed by p cannot be modified (using p) 2) Means that p cannot be changed to point to another object. 3) Means that neither contents of the object pointed by p can be modified nor the object to which p points to. Foot-and-Mouth disease is believed to be the first virus unable to spread through Microsoft Outlook
                1 Reply Last reply
                0
                • J Joaquin M Lopez Munoz

                  1. A reference can not be NULL. Well, this isn't 100% true, but in the real world it is. MyFunc (*(MyClass *) NULL)) is an example of how you can fake it out. However, the programmer had to do work to do that and thus should be shot on site!!! (EDIT: LOL, ... shot on sight.) To the best of my knowledge, the statement that a reference cannot be NULL is 100% true. Dereferencing the null pointer as in (*(MyClass *) NULL) is explicitly marked by the standard as undefined behavior. You cannot rely on this line of code passing unnoticed in run time for every C++ compiler. Joaquín M López Muñoz Telefónica, Investigación y Desarrollo

                  T Offline
                  T Offline
                  Tim Smith
                  wrote on last edited by
                  #23

                  Here is the direct quote from the standard: [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the "object" obtained by dereferencing a null pointer, which cases undefined behavior...] Thus my statement that it isn't 100% true, but in the real world it is. The standard makes no requirement that a reference can not exist. It just says that in a well-defined program it can not exist since the construct required to do it would by definition make a program not well-defined. (IMHO: We are splitting hairs here) Tim Smith Descartes Systems Sciences, Inc.

                  J 1 Reply Last reply
                  0
                  • M Maximilian Hanel

                    Nish [BusterBoy] wrote: Well sometimes you might want to modify the passed pointer. Modifying the passed a pointer within the function actually has no effect to the caller. Therefore you could write the following:

                    void Foo(Bar& bar)
                    {
                    Bar* pBar=&bar;
                    pBar=&SomethingElseForWhatEverReason;
                    }

                    instead of

                    void Foo(Bar* pBar)
                    {
                    pBar=&SomethingElseForWhatEverReason;
                    }

                    But to be honest I'm not really a fan of references. Beleiving that a reference always "points" to something is dangerous:

                    Bar* pBar=NULL;
                    //...
                    Foo(*pBar);

                    So I don't see there a big advantage in using refs. Should we start another religious war? ;P CU Max

                    T Offline
                    T Offline
                    Tim Smith
                    wrote on last edited by
                    #24

                    But to be honest I'm not really a fan of references. Beleiving that a reference always "points" to something is dangerous: Not true at all. The only way to do this gets you into the realm of undefined behavior and thus is inherently bad programming. Tim Smith Descartes Systems Sciences, Inc.

                    M 1 Reply Last reply
                    0
                    • L Lost User

                      Stan Shannon wrote: CBumPhuckEgypt Laughed my fucking arse off at that one. I think the whole function declaration is worthy of signature status. Will have to see if I have the energy to change mine. Michael Martin Australia mmartin@netspace.net.au "Don't belong. Never join. Think for yourself. Peace" - Victor Stone

                      S Offline
                      S Offline
                      Stan Shannon
                      wrote on last edited by
                      #25

                      Thanks, Mick. I thought that was fairly discriptive of some of the code I've had to work on in my lifetime. The biggest problem with pointers is that they give lazy programmers the power to be lazy and get away with it. How's the job search going? If you are still unemployed then you and I are now in the same boat. Except that I just up and quit my job. I intend to spend two or three months living off my savings, mooching off my wife, and upgrading my skills a bit then trying the job market again. I might end up flipping burgers for the rest of my career, and raising my kids as trailer trash, but I've just finally had it with the bad management and unrealistic expectations that pervade the software industry. I think if I can't get something going on my own, I am going to get completely out of the business.

                      L 1 Reply Last reply
                      0
                      • T Tim Smith

                        Here is the direct quote from the standard: [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the "object" obtained by dereferencing a null pointer, which cases undefined behavior...] Thus my statement that it isn't 100% true, but in the real world it is. The standard makes no requirement that a reference can not exist. It just says that in a well-defined program it can not exist since the construct required to do it would by definition make a program not well-defined. (IMHO: We are splitting hairs here) Tim Smith Descartes Systems Sciences, Inc.

                        J Offline
                        J Offline
                        Joaquin M Lopez Munoz
                        wrote on last edited by
                        #26

                        (IMHO: We are splitting hairs here) Sure we are! That's the fun of it ;) Take this lightly, it's obvious that we both know exactly what we're talking bout. So, to continue with this exercise of exegesis, you seem to state that the standard does not say

                        a reference to a null object cannot exist

                        but instead it says

                        a reference to a null object cannot exist in a well-defined program.

                        So the standard implies that

                        references to null objects can only exist in badly-defined programs.

                        Now I'm curious as to what a "well-defined" program is (is it the same as a correct program?) Cheers! Joaquín M López Muñoz Telefónica, Investigación y Desarrollo

                        T 1 Reply Last reply
                        0
                        • S Stan Shannon

                          Thanks, Mick. I thought that was fairly discriptive of some of the code I've had to work on in my lifetime. The biggest problem with pointers is that they give lazy programmers the power to be lazy and get away with it. How's the job search going? If you are still unemployed then you and I are now in the same boat. Except that I just up and quit my job. I intend to spend two or three months living off my savings, mooching off my wife, and upgrading my skills a bit then trying the job market again. I might end up flipping burgers for the rest of my career, and raising my kids as trailer trash, but I've just finally had it with the bad management and unrealistic expectations that pervade the software industry. I think if I can't get something going on my own, I am going to get completely out of the business.

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #27

                          Stan Shannon wrote: How's the job search going? Sat on my arse for the last 2 months and prettty much did fuck all. Had My, Mother In-law, Wifes, Father In-laws and Daughters birthdays in that time so did a lot of preparing and entertaining. Got no savings so spending myself further into debt. Though I did spend a couple of weeks in a factory, the manual non-thinking work was good for a change. Would be doing it now as they came back this week but I have a spasming muscle in my back. Physio trying to fix it now. Have just finished version 0.11 of my résumé and have sent it to a couple of close friends for perusal. After that I will post a link here in the lounge for pointers to get it as shiny as possible and then it's serious job hunting time. Michael Martin Australia mmartin@netspace.net.au "Don't belong. Never join. Think for yourself. Peace" - Victor Stone

                          J R 2 Replies Last reply
                          0
                          • E Eddie Velasquez

                            You forgot to mention that references cannot be "reseated", that is, you can't change the entity the reference "points" to. Foot-and-Mouth disease is believed to be the first virus unable to spread through Microsoft Outlook

                            R Offline
                            R Offline
                            Roger Wright new
                            wrote on last edited by
                            #28

                            Eddie Velasquez wrote: Foot-and-Mouth disease is believed to be the first virus unable to spread through Microsoft Outlook Its close relative, Foot in Mouth disease, does not appear to have this limitation.

                            1 Reply Last reply
                            0
                            • J Joaquin M Lopez Munoz

                              (IMHO: We are splitting hairs here) Sure we are! That's the fun of it ;) Take this lightly, it's obvious that we both know exactly what we're talking bout. So, to continue with this exercise of exegesis, you seem to state that the standard does not say

                              a reference to a null object cannot exist

                              but instead it says

                              a reference to a null object cannot exist in a well-defined program.

                              So the standard implies that

                              references to null objects can only exist in badly-defined programs.

                              Now I'm curious as to what a "well-defined" program is (is it the same as a correct program?) Cheers! Joaquín M López Muñoz Telefónica, Investigación y Desarrollo

                              T Offline
                              T Offline
                              Thomas Freudenberg
                              wrote on last edited by
                              #29

                              Joaquín M López Muñoz wrote: Now I'm curious as to what a "well-defined" program is (is it the same as a correct program?) Obviously, a well-defined program is a program, where no references to null objects exist. ;P Regards Thomas Finally with Sonork id: 100.10453 Thömmi


                              Disclaimer:
                              Because of heavy processing requirements, we are currently using some of your unused brain capacity for backup processing. Please ignore any hallucinations, voices or unusual dreams you may experience. Please avoid concentration-intensive tasks until further notice. Thank you.

                              1 Reply Last reply
                              0
                              • S S Spenz

                                What do you like more in your code? Functions with pointers or references parameters? I don't talk about required e.g. API function stuff but about self-defined functions. I think pointers look much better than this ugly & ;) . Of course sometimes you have no choice but if what would you choose? ----------------------------------------- I'm a signature virus. Copy me to your sig and help me spread...

                                J Offline
                                J Offline
                                James R Twine
                                wrote on last edited by
                                #30

                                S. Spenz wrote: What do you like more in your code? Functions with pointers or references parameters?    Here is a small often overlooked thought:  Consider that you are building a DLL for external use by others.  Do you use pointers or references in your parameter lists?    (Possible reason why you should not: the C++ standard says that the implementation of references is implementation-dependent, meaning depending largly on you compiler suite, correct?  So what happens when code generated with one compiler tries to use code generated by another? Like Borland <-> CV++, or VC++ <-> MinGW?)    Peace! -=- James.

                                J 1 Reply Last reply
                                0
                                • J James R Twine

                                  S. Spenz wrote: What do you like more in your code? Functions with pointers or references parameters?    Here is a small often overlooked thought:  Consider that you are building a DLL for external use by others.  Do you use pointers or references in your parameter lists?    (Possible reason why you should not: the C++ standard says that the implementation of references is implementation-dependent, meaning depending largly on you compiler suite, correct?  So what happens when code generated with one compiler tries to use code generated by another? Like Borland <-> CV++, or VC++ <-> MinGW?)    Peace! -=- James.

                                  J Offline
                                  J Offline
                                  Joaquin M Lopez Munoz
                                  wrote on last edited by
                                  #31

                                  If only references were the greatest problem in intercompiler communication! (sigh) Unfortunately (or not?), there's an enormous set of implementation details due to wich which code generated by two compilers can not be mixed. To name a few: name mangling, member function calling convention, class layout, virtual table implementation... Reference implementation is but a tiny drop of water in the middle of this ocean of incompatibilities. In case you're interested, there's some effort going on on different forums about the problem of defining a compiler interoperable C++ Aplication Binary Interface. Lots of info on the net, just type "C++ ABI" in your favorite search engine. Joaquín M López Muñoz Telefónica, Investigación y Desarrollo

                                  J 1 Reply Last reply
                                  0
                                  • L Lost User

                                    Stan Shannon wrote: How's the job search going? Sat on my arse for the last 2 months and prettty much did fuck all. Had My, Mother In-law, Wifes, Father In-laws and Daughters birthdays in that time so did a lot of preparing and entertaining. Got no savings so spending myself further into debt. Though I did spend a couple of weeks in a factory, the manual non-thinking work was good for a change. Would be doing it now as they came back this week but I have a spasming muscle in my back. Physio trying to fix it now. Have just finished version 0.11 of my résumé and have sent it to a couple of close friends for perusal. After that I will post a link here in the lounge for pointers to get it as shiny as possible and then it's serious job hunting time. Michael Martin Australia mmartin@netspace.net.au "Don't belong. Never join. Think for yourself. Peace" - Victor Stone

                                    J Offline
                                    J Offline
                                    jkgh
                                    wrote on last edited by
                                    #32

                                    Sorry to but in but .. good luck to both of you. I've enjoyed reading your combined posts for the last year or so. Kind regards.

                                    1 Reply Last reply
                                    0
                                    • L Lost User

                                      Stan Shannon wrote: How's the job search going? Sat on my arse for the last 2 months and prettty much did fuck all. Had My, Mother In-law, Wifes, Father In-laws and Daughters birthdays in that time so did a lot of preparing and entertaining. Got no savings so spending myself further into debt. Though I did spend a couple of weeks in a factory, the manual non-thinking work was good for a change. Would be doing it now as they came back this week but I have a spasming muscle in my back. Physio trying to fix it now. Have just finished version 0.11 of my résumé and have sent it to a couple of close friends for perusal. After that I will post a link here in the lounge for pointers to get it as shiny as possible and then it's serious job hunting time. Michael Martin Australia mmartin@netspace.net.au "Don't belong. Never join. Think for yourself. Peace" - Victor Stone

                                      R Offline
                                      R Offline
                                      Roger Allen
                                      wrote on last edited by
                                      #33

                                      Michael Martin wrote: then it's serious job hunting time Sorry, I am still not available to attend interviews for you :-D Roger Allen Sonork 100.10016

                                      L 1 Reply Last reply
                                      0
                                      • T Tim Smith

                                        But to be honest I'm not really a fan of references. Beleiving that a reference always "points" to something is dangerous: Not true at all. The only way to do this gets you into the realm of undefined behavior and thus is inherently bad programming. Tim Smith Descartes Systems Sciences, Inc.

                                        M Offline
                                        M Offline
                                        Maximilian Hanel
                                        wrote on last edited by
                                        #34

                                        Tim Smith wrote: Not true at all. The only way to do this gets you into the realm of undefined behavior and thus is inherently bad programming. I totally agree with you that passing a "NULL reference" is bad programming. But what's the difference in passing a NULL reference and passing a NULL pointer? IMHO passing a NULL pointer is as bad as passing a "NULL reference". Passing a "NULL reference" results in an so called "undefined behaviour" (in other words the programm may crash) and passing NULL pointer results in a "defined behaviour" (the programm defenitely will crash). So why should references be safer than pointers? Assume there is an existing function called GetBar wich returns a pointer to a CBar. Additionally you wrote your own function Baz wich accepts a reference to a CBar:

                                        CBar* GetBar();
                                        void Baz(CBar& bar);
                                        //[...]
                                        CBar* pBar=GetBar();
                                        Baz(*pBar);

                                        Is Baz now "safer" because we accept a reference to a CBar instead of a pointer to CBar? I don't think so. Please don't get me wrong. I'm not the person who tells the world not using references. I'm using references, too (but I'm not a fan). The point is that references IMHO are not in the least safer than pointers. Maybe the chance that you pass a "NULL reference" is more less. But this doesn't make a reference itself safer. Have a nice day Max

                                        1 Reply Last reply
                                        0
                                        • J Joaquin M Lopez Munoz

                                          If only references were the greatest problem in intercompiler communication! (sigh) Unfortunately (or not?), there's an enormous set of implementation details due to wich which code generated by two compilers can not be mixed. To name a few: name mangling, member function calling convention, class layout, virtual table implementation... Reference implementation is but a tiny drop of water in the middle of this ocean of incompatibilities. In case you're interested, there's some effort going on on different forums about the problem of defining a compiler interoperable C++ Aplication Binary Interface. Lots of info on the net, just type "C++ ABI" in your favorite search engine. Joaquín M López Muñoz Telefónica, Investigación y Desarrollo

                                          J Offline
                                          J Offline
                                          James R Twine
                                          wrote on last edited by
                                          #35

                                          Joaquín M López Muñoz wrote: Unfortunately (or not?), there's an enormous set of implementation details due to wich which code generated by two compilers can not be mixed. To name a few: name mangling, member function calling convention, class layout, virtual table implementation... Reference implementation is but a tiny drop of water in the middle of this ocean of incompatibilities.    That assumes that I am only talking about exporting entire classes, or member functions.    I am just talking about doing things as simple as just writing a "plain" DLL that exports a few non-member functions (which can be referenced by ordinal, or alias).  Why do I ask about this?  Because I have seen it done before :(    I just wanted to hear other thoughts on the wisdom (or lack of) in doing so.    Peace! -=- James.

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups