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.
  • 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
    Joaquin M Lopez Munoz
    wrote on last edited by
    #2

    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 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 Pullicino
      wrote on last edited by
      #3

      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)

      C E 2 Replies 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)

        C Offline
        C Offline
        Chris Maunder
        wrote on last edited by
        #4

        My only beef with references is not having the syntactic hint that the parameter you are passing in may be subject to change from within. The ref keyword in C# is a Godsend for those of us with weak memories. cheers, Chris Maunder

        C 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...

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

          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 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...

            N Offline
            N Offline
            Nish Nishant
            wrote on last edited by
            #6

            Well sometimes you might want to modify the passed pointer. Not the contents but the pointer itself. You cannot do that with a reference which is a const pointer. Nish Sonork ID 100.9786 voidmain www.busterboy.org If you don't find me on CP, I'll be at Bob's HungOut

            T M 2 Replies Last reply
            0
            • N Nish Nishant

              Well sometimes you might want to modify the passed pointer. Not the contents but the pointer itself. You cannot do that with a reference which is a const pointer. Nish Sonork ID 100.9786 voidmain www.busterboy.org If you don't find me on CP, I'll be at Bob's HungOut

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

              How about a pointer to a reference?

              void foo(bar*& x);

              or even a pointer to constant reference?

              void foo(bar* const& x);

              or... X| 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...

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

                References. Pointers pave the road to hell.:eek:

                1 Reply Last reply
                0
                • N Nish Nishant

                  Well sometimes you might want to modify the passed pointer. Not the contents but the pointer itself. You cannot do that with a reference which is a const pointer. Nish Sonork ID 100.9786 voidmain www.busterboy.org If you don't find me on CP, I'll be at Bob's HungOut

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

                  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

                  J T 2 Replies 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

                    J Offline
                    J Offline
                    James Pullicino
                    wrote on last edited by
                    #10

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

                    S M 2 Replies Last reply
                    0
                    • 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)

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

                      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 1 Reply Last reply
                      0
                      • C Chris Maunder

                        My only beef with references is not having the syntactic hint that the parameter you are passing in may be subject to change from within. The ref keyword in C# is a Godsend for those of us with weak memories. cheers, Chris Maunder

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

                        Stroustrup is against using references for a passed parameter when a function changes the reference's content as well. I don't know -- I have gone back and forth on this in my own code. I still tend to like references better since it gets rid of all the pointer dereferencing inside my functions. Better for the function writer, not as good for the function user. C# probably does have the advantage of hindsight on this issue. CodeGuy The WTL newsgroup: over 1100 members! Be a part of it. http://groups.yahoo.com/group/wtl

                        T 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...

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

                          It is all a question of style. Don't believe this junk about pointers being bad. Like everything, bad programmers will always find ways of screwing up good things. But some people have made some very good points about references. Here are the rules I use. 1. If the argument is read-only, pass by const reference. 2. If the argument is read-write, pass by pointer and sometimes a reference. 3. If the argument is write-only, pass by pointer. The reason is purely based on style. The idea is that by making an argument that will be written to a pointer, you are providing a hint that the value will be modified. IMHO, it is poor style to pass arguments that will be modified by reference. Some very good points I have seen from other people. 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.) 2. When passing by reference, there isn't the ambiguity that a pointer is pointing to one or an array of elements. But, you shouldn't be passing an array by pointer without the size of the array being supplied. Tim Smith Descartes Systems Sciences, Inc.

                          J 1 Reply Last reply
                          0
                          • C CodeGuy

                            Stroustrup is against using references for a passed parameter when a function changes the reference's content as well. I don't know -- I have gone back and forth on this in my own code. I still tend to like references better since it gets rid of all the pointer dereferencing inside my functions. Better for the function writer, not as good for the function user. C# probably does have the advantage of hindsight on this issue. 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
                            #14

                            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 1 Reply Last reply
                            0
                            • T Tim Smith

                              It is all a question of style. Don't believe this junk about pointers being bad. Like everything, bad programmers will always find ways of screwing up good things. But some people have made some very good points about references. Here are the rules I use. 1. If the argument is read-only, pass by const reference. 2. If the argument is read-write, pass by pointer and sometimes a reference. 3. If the argument is write-only, pass by pointer. The reason is purely based on style. The idea is that by making an argument that will be written to a pointer, you are providing a hint that the value will be modified. IMHO, it is poor style to pass arguments that will be modified by reference. Some very good points I have seen from other people. 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.) 2. When passing by reference, there isn't the ambiguity that a pointer is pointing to one or an array of elements. But, you shouldn't be passing an array by pointer without the size of the array being supplied. Tim Smith Descartes Systems Sciences, Inc.

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

                              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 1 Reply Last reply
                              0
                              • 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
                                          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