reference, pointers and copy's

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • themadme
    New Member
    • Mar 2007
    • 53

    reference, pointers and copy's

    i know that when passing a class/struct or anything quite large of an object through a parameter by reference is a lot more sufficient than copying, same thing goes for returning it by reference.

    How about the small variables, like int's and floats as well as strings. Would it be more sufficient to pass it by reference or just copying it over? same thing goes for returning?

    or does this depend on what you are going to do with the member? or does it not make a significant difference.

    forgive me for my little lack of knowledge on this area
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    Primitives can probably be passed by copy most of the time, unless they need to be changed, in which case they should be passed by pointer or reference. I prefer reference in C++, as it avoids the mess pointers can create. Strings and any other object (structs, classes) should be passed by reference at all times. Note that pointers should themselves be passed by reference if the pointer itself is to be changed.

    Comment

    • themadme
      New Member
      • Mar 2007
      • 53

      #3
      thanks you for your reply.

      Agree what you have said but is copying more expensive to do than have a const reference? if you don't want anything to change

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Copying is generally more expensive than using a reference.

        You use a reference when you intend to change the value of the argument. Since the reference is an alias for the original variable, itis the original variable that is changed.

        That means if you need to refer to multiple variables in your function using the same argument, you cannot use a reference. You have to use a pointer.

        Comment

        • themadme
          New Member
          • Mar 2007
          • 53

          #5
          thank you for replying

          Comment

          • dtimes6
            New Member
            • Oct 2006
            • 73

            #6
            I have remembered that a Book by Stan Lippman Essential C++ talk about this.

            It is suggested to use reference as much as you can in C++. For the old C types there is no differece if you use reference or not.

            Comment

            Working...