reference and pointer and function argument copy

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • joel.winteregg@gmail.com

    #1

    reference and pointer and function argument copy

    Hi all,


    I "learnt" C++ a few years ago and then i have been using C for a
    couple of month and i'm now trying to get back to the ++ world (but
    with some troubles...). I have some problem to understand why a "new"
    return a pointer and not a reference. Here are explanations:


    /* to get my object in heap */
    MyClass* objectPtr = new MyClass();

    If i want to handle my object using a reference i will have to do
    something like this:

    MyClass& objectRef = *objectPtr;
    /* or all in one */
    MyClass& objectRef = *(new MyClass());

    Why the use of "new" wasn't done to get reference and malloc to get
    pointers ? wouldn't it be easier ?

    I also have an other question about function call using references.
    During my search i have been reading this post:


    which confuse me a lot. Is it right that a function which return an
    object ref will return it using the copy constructor (a copy of it ) ?

    MyClass& GetMyClass() { return myObject; }
    MyClass& myObj = GetMyClass();

    I thought that the "return MyClass" statement would return the ref of
    "myObject" and not a copy of it !! (Hope the object was allocated using
    new and not statically ;-) )

    I would do it by copy, like this:

    MyClass GetMyClass() { return myObject; }
    /* object statically allocated */
    MyClass myObj = GetMyClass();

    Thanks a lot for your help !!

    Joël

  • Alf P. Steinbach

    #2
    Re: reference and pointer and function argument copy

    * joel.winteregg@ gmail.com:
    >
    I "learnt" C++ a few years ago and then i have been using C for a
    couple of month and i'm now trying to get back to the ++ world (but
    with some troubles...). I have some problem to understand why a "new"
    return a pointer and not a reference.
    Mostly it's a convention, that dynamically allocated objects are
    referred to via pointers, not references. But there's also a historical
    part (pre-standard compilers could let new return a nullpointer instead
    of throwing an exception) and a consistency issue (new(nothrow) does
    return a nullpointer instead of throwing an exception). Ideally, in a
    language designed from scratch, new should perhaps return a reference.

    Here are explanations:
    >
    /* to get my object in heap */
    MyClass* objectPtr = new MyClass();
    >
    If i want to handle my object using a reference i will have to do
    something like this:
    >
    MyClass& objectRef = *objectPtr;
    /* or all in one */
    MyClass& objectRef = *(new MyClass());
    >
    Why the use of "new" wasn't done to get reference and malloc to get
    pointers ? wouldn't it be easier ?
    'new' and 'malloc' do very different things. The main difference isn't
    the result type, but that 'new' is the C++ device for calling a
    constructor on some storage, transforming that storage into a valid
    object. The ordinary 'new' guarantees that on successful execution you
    have an initialized object at hand, and otherwise (an exception occurs)
    that the allocated memory is freed; 'malloc' just allocates memory.

    I also have an other question about function call using references.
    During my search i have been reading this post:

    >
    which confuse me a lot. Is it right that a function which return an
    object ref will return it using the copy constructor (a copy of it ) ?
    No. It just returns a reference to whatever you specify. Which should
    be an object that doesn't cease to exist when the function returns.

    MyClass& GetMyClass() { return myObject; }
    MyClass& myObj = GetMyClass();
    >
    I thought that the "return MyClass" statement would return the ref of
    "myObject" and not a copy of it !!
    It does.

    (Hope the object was allocated using
    new and not statically ;-) )
    It doesn't matter how the object was allocated, except if that means the
    object won't exist after the function return (in which case you have a
    dangling reference, not a good idea).

    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is it such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet and in e-mail?

    Comment

    • joel.winteregg@gmail.com

      #3
      Re: reference and pointer and function argument copy

      Why the use of "new" wasn't done to get reference and malloc to get
      pointers ? wouldn't it be easier ?
      >
      'new' and 'malloc' do very different things. The main difference isn't
      the result type, but that 'new' is the C++ device for calling a
      constructor on some storage, transforming that storage into a valid
      object. The ordinary 'new' guarantees that on successful execution you
      have an initialized object at hand, and otherwise (an exception occurs)
      that the allocated memory is freed; 'malloc' just allocates memory.
      Yesss, sure !! sorry for the stupid question... i was just thinking
      about return type :-(

      which confuse me a lot. Is it right that a function which return an
      object ref will return it using the copy constructor (a copy of it ) ?
      >
      No. It just returns a reference to whatever you specify. Which should
      be an object that doesn't cease to exist when the function returns.
      Oufffff !! i will sleep well now !! (i just did a test using a simple
      class after my post to rest my mind...)
      >
      It doesn't matter how the object was allocated, except if that means the
      object won't exist after the function return (in which case you have a
      dangling reference, not a good idea).
      Took me a few seconds to understand what you mean ! but i think i get
      it... for me the statically allocated == on stack which mean it is
      automaticaly cleaned after the function call -problem if you return
      the ref of it. And dynamical == on heap -OK for ever. But i think
      that your sentence say that even if it's done on heap you can have
      problems if you do a delete of the object before the function return it
      ;-). Is it your sentence translation ?

      Thanks a lot for you help !

      Jo

      Comment

      • Frederick Gotham

        #4
        Re: reference and pointer and function argument copy

        Joel posted:
        Hi all,
        >
        >
        I "learnt" C++ a few years ago and then i have been using C for a
        couple of month and i'm now trying to get back to the ++ world (but
        with some troubles...). I have some problem to understand why a "new"
        return a pointer and not a reference.

        There's nothing to understand -- it just does.

        Here are explanations:
        >
        >
        /* to get my object in heap */
        MyClass* objectPtr = new MyClass();

        You'll probably want to make that const if you intend on deleting it later:


        MyClass *const p = ...

        If i want to handle my object using a reference i will have to do
        something like this:
        >
        MyClass& objectRef = *objectPtr;
        /* or all in one */
        MyClass& objectRef = *(new MyClass());

        MyClass &r = *new MyClass;

        Why the use of "new" wasn't done to get reference and malloc to get
        pointers ? wouldn't it be easier ?

        Not when it comes to arrays.

        --

        Frederick Gotham

        Comment

        • Richard

          #5
          Re: reference and pointer and function argument copy

          Frederick Gotham <fgothamNO@SPAM .comwrites:
          Joel posted:
          >
          >Hi all,
          >>
          >>
          >I "learnt" C++ a few years ago and then i have been using C for a
          >couple of month and i'm now trying to get back to the ++ world (but
          >with some troubles...). I have some problem to understand why a "new"
          >return a pointer and not a reference.
          >
          >
          There's nothing to understand -- it just does.
          >
          >
          >Here are explanations:
          >>
          >>
          >/* to get my object in heap */
          >MyClass* objectPtr = new MyClass();
          >
          >
          You'll probably want to make that const if you intend on deleting it later:
          >
          >
          MyClass *const p = ...
          >
          Out of curiosity, what has making it a const got to do with deleting it later?

          Comment

          • Frederick Gotham

            #6
            Re: reference and pointer and function argument copy

            Richard posted:
            >You'll probably want to make that const if you intend on deleting it
            >later:
            >>
            >>
            >MyClass *const p = ...
            >>
            >
            Out of curiosity, what has making it a const got to do with deleting it
            later?

            You must supply "delete" with the same address returned from "new". By
            defining the variable as const, you make sure that the address won't
            change.

            The following compiles no problem:

            int *p = new int[5];

            ++p;

            delete [] p;

            However, the following fails to compile:

            int *const p = new int[5];

            ++p; /* Const violation */

            delete [] p;

            I bring this concept further to define functions whose return value is
            const:

            int *const Func()
            {
            return new int[5];
            }

            It doesn't really buy you anything, but it's intuitive.

            --

            Frederick Gotham

            Comment

            • Victor Bazarov

              #7
              Re: reference and pointer and function argument copy

              Frederick Gotham wrote:
              [...]
              I bring this concept further to define functions whose return value is
              const:
              >
              int *const Func()
              {
              return new int[5];
              }
              >
              It doesn't really buy you anything, but it's intuitive.
              How is it intuitive? I would consider using it _only_ if the following
              failed to compile.

              int * p = Func();
              ++p;
              delete[] p;

              V
              --
              Please remove capital 'A's when replying by e-mail
              I do not respond to top-posted replies, please don't ask


              Comment

              • Richard

                #8
                Re: reference and pointer and function argument copy

                Frederick Gotham <fgothamNO@SPAM .comwrites:
                Richard posted:
                >
                >>You'll probably want to make that const if you intend on deleting it
                >>later:
                >>>
                >>>
                >>MyClass *const p = ...
                >>>
                >>
                >Out of curiosity, what has making it a const got to do with deleting it
                >later?
                >
                >
                You must supply "delete" with the same address returned from "new". By
                defining the variable as const, you make sure that the address won't
                change.
                Aha, so it doesnt actually have anything to do with the delete. You just
                want to make sure the pointer doesnt change. No worries.

                Comment

                • Frederick Gotham

                  #9
                  Re: reference and pointer and function argument copy

                  Victor Bazarov posted:
                  Frederick Gotham wrote:
                  >[...]
                  >I bring this concept further to define functions whose return value is
                  >const:
                  >>
                  > int *const Func()
                  > {
                  > return new int[5];
                  > }
                  >>
                  >It doesn't really buy you anything, but it's intuitive.
                  >
                  How is it intuitive? I would consider using it _only_ if the following
                  failed to compile.
                  >
                  int * p = Func();
                  ++p;
                  delete[] p;
                  >
                  V

                  It's just another way of writing:

                  int *Func() /* Remember to keep track of the address */
                  {
                  return new int[5];
                  }

                  --

                  Frederick Gotham

                  Comment

                  Working...