why reference ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • William Xuuu

    #1

    why reference ?


    Hi,

    References introduced make things much more complicated. e.g.

    int a;
    void f(int &n);
    void g(int *p);

    Isn't g(&a) much more clear than f(a), when we would change the value of
    the lvalue a ?

    Are there any efficiency differences ?

    Is reference a must in c++ ?

    thanks.

    --
    William Xuuu
  • Karl Heinz Buchegger

    #2
    Re: why reference ?

    William Xuuu wrote:[color=blue]
    >
    > Hi,
    >
    > References introduced make things much more complicated. e.g.
    >
    > int a;
    > void f(int &n);
    > void g(int *p);
    >
    > Isn't g(&a) much more clear than f(a), when we would change the value of
    > the lvalue a ?[/color]

    Clearity is in the eye of the beholder :-)
    Seriously. It depends. In your above example it definitly is
    not clear to the caller if

    f(a)

    will change 'a' or not.

    But in practice this is much less an issue then you think. Mostly
    because in real life functions are not called 'f' and arguments are
    not called 'a'. In

    j = CalcFibonacci( InputNumber );

    will the function CalcFibonacci alter the passed argument? While
    there is no 100% guarantee, bets are good, that it won't.

    Same for eg. the prototype

    void Deposit( Account& TheAccount, long Amount );

    Now guess: Will The Account be changed when the function is called.
    If you read the callers code:

    Account CustomerAccount ;
    long Amount;

    CustomerAccount = AskForCustomer( );
    Amount = AskForAmount();

    Deposit( CustomerAccount , Amount );

    When you read that code, and have no idea that the first argument
    to Deposit is passed by reference, would you expect CustomerAccount
    to change? Sure I would! If I deposit something on an account, then
    the amount associated with that account changes.
    [color=blue]
    >
    > Are there any efficiency differences ?[/color]

    When you pass a pointer, it is the functions responsibility to at
    least check that the passed pointer is not 0. On the other hand,
    if you pass per reference AND the function gets inlined, you open
    a lot of possibilities for the compiler for optimizations.
    [color=blue]
    >
    > Is reference a must in c++ ?[/color]

    Yes. Otherwise writing custom operators would not be possible.
    Granted, we could live without that feature (although it is a
    nice one) and then AFAIK there would be no killer argument for
    not dropping references.

    --
    Karl Heinz Buchegger
    kbuchegg@gascad .at

    Comment

    • Tim Love

      #3
      Re: why reference ?

      William Xuuu <william_xuuu@1 63.com> writes:

      [color=blue]
      >Hi,[/color]
      [color=blue]
      >References introduced make things much more complicated.[/color]
      See

      [color=blue]
      >Is reference a must in c++ ?[/color]
      In some situations, yes I think so.

      Comment

      • Thomas Barth

        #4
        Re: why reference ?

        >[color=blue]
        > Are there any efficiency differences ?
        >
        > Is reference a must in c++ ?
        >[/color]

        Reference variables can be created for local use as aliases
        for other variables within a function. Reference variables must
        be initialized in their declarations, and they cannot be reassigned
        as aliases to other variables. Once a reference variable is
        declared as an alias for another variable, all operations performed
        on the alias actually are performed on the variable.
        As a former java-coder I can say that pointers are needless :-)

        Thomas B.


        Comment

        • Tilman Kuepper

          #5
          Re: why reference ?

          Hi William,
          [color=blue]
          > Isn't g(&a) much more clear than f(a), when we would change
          > the value of the lvalue a ?
          >
          > Are there any efficiency differences ?[/color]

          If a function has to change a variable via a pointer, the function
          has to check for null-pointers first. For example...

          void Change(int* pVal)
          {
          if(pVal)
          *pVal = 123;
          else
          throw SomeException;
          }

          Okay, but perhaps you are writing a function where it is
          not allowed to pass null-pointers as parameters. In this
          case you have to add some documentation to your function
          where this pre-condition is described. You should still
          use assert() before accessing the pointer, though...

          With references all this is not necessary. If you declare
          a function like...

          void Change(int& val);

          ....then it is simply not possible to call this function with a
          null-pointer.

          Tilman



          Comment

          • John Harrison

            #6
            Re: why reference ?


            "William Xuuu" <william_xuuu@1 63.com> wrote in message
            news:87y8h218kb .fsf@163.com...[color=blue]
            >
            > Hi,
            >
            > References introduced make things much more complicated. e.g.
            >
            > int a;
            > void f(int &n);
            > void g(int *p);
            >
            > Isn't g(&a) much more clear than f(a), when we would change the value of
            > the lvalue a ?
            >
            > Are there any efficiency differences ?
            >
            > Is reference a must in c++ ?[/color]

            Try writing an assignment operator using a pointer.

            class X
            {
            X& operator=(const X* rhs);
            };

            Then you would then have to write

            X x, y;
            x = &y;

            Do you think that is good style?

            References and pointers are different. The main difference is that a
            reference once initialised cannot be made to refer to something else. This
            is often exactly what you want, and makes using references very common, it
            also makes the syntax simpler.

            john


            Comment

            • Gernot Frisch

              #7
              Re: why reference ?


              [color=blue]
              > As a former java-coder I can say that pointers are needless :-)[/color]

              double GetFirstNegativ e(double* pNums)
              {
              while(*pNums>0. 0) ++pNums;
              return *pNums;
              }

              Try that with references and compare the assembly generated.


              Comment

              • Arijit

                #8
                Re: why reference ?

                Gernot Frisch wrote:[color=blue]
                >
                > double GetFirstNegativ e(double* pNums)
                > {
                > while(*pNums>0. 0) ++pNums;
                > return *pNums;
                > }
                >
                > Try that with references and compare the assembly generated.
                >
                >[/color]

                How about:

                double GetFirstNegativ e(double* pNums)
                {
                int i=0;
                while(pNums[i]>0.0)
                ++i;
                return pNums[i];
                }

                No pointers, no references. Agreed, has an extra variable.

                It is very rare in C++ that a pointer is truly needed. Almost all the
                time you can get around using references or [].


                --
                X-Privat Project - http://www.newsserver.it/

                Comment

                • Thomas Barth

                  #9
                  Re: why reference ?

                  Hi
                  [color=blue]
                  >
                  > double GetFirstNegativ e(double* pNums)
                  > {
                  > int i=0;
                  > while(pNums[i]>0.0)
                  > ++i;
                  > return pNums[i];
                  > }
                  >[/color]

                  Pointer free, array passed by reference

                  double getFirstNegativ e(double arr[]) {


                  Thomas B.



                  Comment

                  • Jon Bell

                    #10
                    Re: why reference ?

                    In article <87y8h218kb.fsf @163.com>,
                    William Xuuu <william_xuuu@1 63.com> wrote:[color=blue]
                    >
                    >References introduced make things much more complicated. e.g.[/color]

                    That depends on your point of view. :-)

                    I came to C++ from Fortran and Pascal, which use reference semantics
                    (although not the same syntax as C++ of course) for passing data to
                    functions. I find references to be natural to use, whereas pointers are
                    cumbersome and error-prone.

                    --
                    Jon Bell <jtbellm4h@pres by.edu> Presbyterian College
                    Dept. of Physics and Computer Science Clinton, South Carolina USA

                    Comment

                    • Thomas Barth

                      #11
                      Re: why reference ?

                      And you should always consider the size of an array

                      double getFirstNegativ e(double arr[], int &iSize) {
                      double dValue = 0.0;
                      for (int i = 0; i < iSize && dValue == 0.0; i++) {
                      if(arr[i] < 0.0) dValue = arr[i];
                      }
                      return dValue;
                      }

                      I am not a friend of code compression :-) Your code versions
                      would throw an OutOfBound-exception

                      Thomas B.


                      Comment

                      • Julián Albo

                        #12
                        Re: why reference ?

                        William Xuuu wrote:
                        [color=blue]
                        > int a;
                        > void f(int &n);
                        > void g(int *p);
                        >
                        > Isn't g(&a) much more clear than f(a), when we would change the value of
                        > the lvalue a ?[/color]

                        Yes, but if you name the function evaluate_someth ing instead of f things
                        will be much more clear.

                        --
                        Salu2

                        Comment

                        • Andrew Koenig

                          #13
                          Re: why reference ?


                          "Julián Albo" <JULIANALBO@ter ra.es> wrote in message
                          news:2vum7iF2or oooU2@uni-berlin.de...[color=blue]
                          > William Xuuu wrote:
                          >[color=green]
                          >> int a;
                          >> void f(int &n);
                          >> void g(int *p);
                          >>
                          >> Isn't g(&a) much more clear than f(a), when we would change the value of
                          >> the lvalue a ?[/color]
                          >
                          > Yes, but if you name the function evaluate_someth ing instead of f things
                          > will be much more clear.[/color]

                          For example:

                          std::cin >> a;

                          Isn't this clearer than having to write

                          std::cin >> &a;

                          ?


                          Comment

                          • Lionel B

                            #14
                            Re: why reference ?

                            John Harrison wrote:[color=blue]
                            > References and pointers are different. The main difference is that a
                            > reference once initialised cannot be made to refer to something else.[/color]

                            ....and perhaps equally important (as several posters have pointed out),
                            a reference *must* be initialised.

                            And hence may be assumed to refer to something sensible... oops, maybe
                            not:

                            int* p = new int(5);
                            int& i = *p;
                            delete p;

                            I note that the following program:

                            <CODE>

                            #include <iostream>

                            int main()
                            {
                            int* p = new int(5);
                            int& i = *p;
                            std::cout << "i = " << i << '\n';
                            delete p;
                            p = new int(6);
                            std::cout << "i = " << i << '\n';
                            delete p;
                            return 0;
                            }

                            </CODE>

                            outputs:

                            i = 5;
                            i = 6;

                            on my system - but I suspect that this is actually UB and it is
                            fortuitous that the second new allocated the same address as the
                            first...

                            --
                            Lionel B

                            Comment

                            • Arijit

                              #15
                              Re: why reference ?

                              Thomas Barth wrote:[color=blue]
                              > And you should always consider the size of an array
                              >
                              > double getFirstNegativ e(double arr[], int &iSize) {
                              > double dValue = 0.0;
                              > for (int i = 0; i < iSize && dValue == 0.0; i++) {
                              > if(arr[i] < 0.0) dValue = arr[i];
                              > }
                              > return dValue;
                              > }
                              >
                              > I am not a friend of code compression :-) Your code versions
                              > would throw an OutOfBound-exception
                              >
                              > Thomas B.
                              >[/color]

                              I was replying to Gernot's post. I made as minimal changes as possible
                              to the program to get to it work without pointers.

                              Actually, my code will not throw any exception, the whole thing will
                              just crash. On Linux, probably the famous "Segmentati on fault. Core dumped."

                              -Arijit


                              Comment

                              Working...