DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: Returning a reference, pointer or an object

  1. #1
    Kent Guest

    Returning a reference, pointer or an object


    Hi All,

    I have a question concerning return values from a C++ method. What is the
    usual way of returning an object?

    For example, suppose I am writing a method called getDirectory() which returns
    the installation directory of my app. Being a Java programmer I am used to
    writing code like:

    String getDirectory() {
    return (dir); //where dir is a String reference
    }

    In C++, however, there are - as I see it - several choices:

    1. Return a copy of a CString: CString getDirectory();

    2. Return a reference to a CString: CString& getDirectory();

    3. Return a pointer to a CString: CString* getDirectory();

    4. Return a reference to a CString but also take the CString as a parameter:
    CString& getDirectory(CString& buffer);


    Option 1 is inefficient as it requires a copy of the CString to be made.

    I'm not sure if option 2 is feasible given that the CString would have to
    be created within the method. Is it a good idea to allocate a new CString
    on the heap and return a reference to it - I'm assuming not?

    Option 3 has the same issue as 2 - the CString needs to be allocated within
    the method.

    Option 4 seems feasible but cumbersome - is this the standard way of doing
    things?

    Thanks,
    Kent

  2. #2
    Danny Kalev Guest

    Re: Returning a reference, pointer or an object



    Kent wrote:
    >
    > Hi All,
    >
    > I have a question concerning return values from a C++ method. What is the
    > usual way of returning an object?
    >
    > For example, suppose I am writing a method called getDirectory() which returns
    > the installation directory of my app. Being a Java programmer I am used to
    > writing code like:
    >
    > String getDirectory() {
    > return (dir); //where dir is a String reference
    > }
    >
    > In C++, however, there are - as I see it - several choices:


    In C++, if you want to return an object, you have another option: pass
    the object by reference as a function argument and have the function
    fill it:

    void getDirectory(string &dir)
    {
    dir = blah;
    return dir;
    }

    As a rule of thumb, don't return or pass objects by value because of the
    incurred performance overhead. Using pointers is a mostly a C thing; in
    C++ you should always use references instead of pointers, *unless* a
    NULL value is a valid option.

    Danny

  3. #3
    ralph Guest

    Re: Returning a reference, pointer or an object


    "Kent" <kb@essential.com.au> wrote:
    >
    >Hi All,
    >
    >I have a question concerning return values from a C++ method. What is the
    >usual way of returning an object?
    >
    >For example, suppose I am writing a method called getDirectory() which returns
    >the installation directory of my app. Being a Java programmer I am used

    to
    >writing code like:
    >
    >String getDirectory() {
    > return (dir); //where dir is a String reference
    >}
    >
    >In C++, however, there are - as I see it - several choices:
    >
    >1. Return a copy of a CString: CString getDirectory();
    >
    >2. Return a reference to a CString: CString& getDirectory();
    >
    >3. Return a pointer to a CString: CString* getDirectory();
    >
    >4. Return a reference to a CString but also take the CString as a parameter:
    >CString& getDirectory(CString& buffer);
    >
    >
    >Option 1 is inefficient as it requires a copy of the CString to be made.
    >
    >I'm not sure if option 2 is feasible given that the CString would have to
    >be created within the method. Is it a good idea to allocate a new CString
    >on the heap and return a reference to it - I'm assuming not?
    >
    >Option 3 has the same issue as 2 - the CString needs to be allocated within
    >the method.
    >
    >Option 4 seems feasible but cumbersome - is this the standard way of doing
    >things?
    >
    >Thanks,
    >Kent


    The real question is "Who is going to own the storage (memory) for Dir"?

    In Java you didn't care because everything was a reference and carried it's
    own "ownership" you might say. (I will let the language lawyers argue over
    that one. <g>)

    In C++ you can't declare and define something inside a function and 'return'
    it because it longer exists when the routine finishes.

    For a static function option 4 makes more sense as the consumer of the service
    is probably more interested in the life of the 'Dir' string than the fetcher/server.
    Not sure I would bother returning a reference however.

    For a member function that is part of an object that is maintaining ownership
    of 'Dir', simply returning a reference would likely work.

    It may seem "cumbersome" at first, but in C++ you have to shed your training
    wheels, forgo Daddy's hand on your shoulder, and accept some "ownership".
    <smile>

  4. #4
    ch0rlt0n Guest

    Re: Returning a reference, pointer or an object


    Danny Kalev <dannykk@inter.net.il> wrote:
    >
    >
    >
    >In C++, if you want to return an object, you have another option: pass
    >the object by reference as a function argument and have the function
    >fill it:
    >
    > void getDirectory(string &dir)
    > {
    > dir = blah;
    > return dir;
    > }
    >
    >As a rule of thumb, don't return or pass objects by value because of the
    >incurred performance overhead. Using pointers is a mostly a C thing; in
    >C++ you should always use references instead of pointers, *unless* a
    >NULL value is a valid option.
    >
    >Danny


    Sorry Danny, could you clarify whether you intended that function to return
    a string& or be void and _not_ return anything?

    Cheers, ch0rlt0n

  5. #5
    James Curran Guest

    Re: Returning a reference, pointer or an object

    I'd say go with #1 and just accept the (trivial) inefficiency. If the
    function is inlined, it may be optimized away anyway, or it could be negated
    by a reference counted string class (which the CString in VC6 is -- I'm not
    sure about the CString in VC7).

    --
    Truth,
    James Curran
    www.NovelTheory.com (Personal)
    www.NJTheater.com (Professional)
    www.aurora-inc.com (Day job)


    "Kent" <kb@essential.com.au> wrote in message news:3d409c9d$1@10.1.10.29...
    >
    > Hi All,
    >
    > I have a question concerning return values from a C++ method. What is the
    > usual way of returning an object?
    >
    > For example, suppose I am writing a method called getDirectory() which

    returns
    > the installation directory of my app. Being a Java programmer I am used to
    > writing code like:
    >
    > String getDirectory() {
    > return (dir); //where dir is a String reference
    > }
    >
    > In C++, however, there are - as I see it - several choices:
    >
    > 1. Return a copy of a CString: CString getDirectory();
    >
    > 2. Return a reference to a CString: CString& getDirectory();
    >
    > 3. Return a pointer to a CString: CString* getDirectory();
    >
    > 4. Return a reference to a CString but also take the CString as a

    parameter:
    > CString& getDirectory(CString& buffer);
    >
    >
    > Option 1 is inefficient as it requires a copy of the CString to be made.
    >
    > I'm not sure if option 2 is feasible given that the CString would have to
    > be created within the method. Is it a good idea to allocate a new CString
    > on the heap and return a reference to it - I'm assuming not?
    >
    > Option 3 has the same issue as 2 - the CString needs to be allocated

    within
    > the method.
    >
    > Option 4 seems feasible but cumbersome - is this the standard way of doing
    > things?
    >
    > Thanks,
    > Kent




  6. #6
    ralph Guest

    Re: Returning a reference, pointer or an object


    "James Curran" <jamescurran@mvps.org> wrote:
    > I'd say go with #1 and just accept the (trivial) inefficiency. If the
    >function is inlined, it may be optimized away anyway, or it could be negated
    >by a reference counted string class (which the CString in VC6 is -- I'm

    not
    >sure about the CString in VC7).
    >
    >--
    >Truth,
    >James Curran
    >www.NovelTheory.com (Personal)
    >www.NJTheater.com (Professional)
    >www.aurora-inc.com (Day job)
    >


    Reference counting won't do much good when returning the address of a local
    variable.



  7. #7
    James Curran Guest

    Re: Returning a reference, pointer or an object

    True, but irrelevant. Options 2 & 3 have the potential for returning a
    reference to a local which is why I avoided them. Option #1 (my choice)
    returns an full object. Reference counting merely makes that object
    "lighter-weight"


    --
    Truth,
    James Curran
    www.NovelTheory.com (Personal)
    www.NJTheater.com (Professional)
    www.aurora-inc.com (Day job)


    "ralph" <nt_consulting32@hotmail.com> wrote in message
    news:3d414d71$1@10.1.10.29...
    >
    > "James Curran" <jamescurran@mvps.org> wrote:
    > > I'd say go with #1 and just accept the (trivial) inefficiency. If

    the
    > >function is inlined, it may be optimized away anyway, or it could be

    negated
    > >by a reference counted string class (which the CString in VC6 is -- I'm

    > not
    > >sure about the CString in VC7).
    > >
    > >--
    > >Truth,
    > >James Curran
    > >www.NovelTheory.com (Personal)
    > >www.NJTheater.com (Professional)
    > >www.aurora-inc.com (Day job)
    > >

    >
    > Reference counting won't do much good when returning the address of a

    local
    > variable.
    >
    >




  8. #8
    ralph Guest

    Re: Returning a reference, pointer or an object


    "James Curran" <jamescurran@mvps.org> wrote:
    > True, but irrelevant. Options 2 & 3 have the potential for returning

    a
    >reference to a local which is why I avoided them. Option #1 (my choice)
    >returns an full object. Reference counting merely makes that object
    >"lighter-weight"
    >
    >
    >--
    >Truth,
    >James Curran
    >www.NovelTheory.com (Personal)
    >www.NJTheater.com (Professional)
    >www.aurora-inc.com (Day job)
    >
    >
    >"ralph" <nt_consulting32@hotmail.com> wrote in message
    >news:3d414d71$1@10.1.10.29...
    >>
    >> "James Curran" <jamescurran@mvps.org> wrote:
    >> > I'd say go with #1 and just accept the (trivial) inefficiency. If

    >the
    >> >function is inlined, it may be optimized away anyway, or it could be

    >negated
    >> >by a reference counted string class (which the CString in VC6 is -- I'm

    >> not
    >> >sure about the CString in VC7).
    >> >
    >> >--
    >> >Truth,
    >> >James Curran
    >> >www.NovelTheory.com (Personal)
    >> >www.NJTheater.com (Professional)
    >> >www.aurora-inc.com (Day job)
    >> >

    >>
    >> Reference counting won't do much good when returning the address of a

    >local
    >> variable.
    >>


    Yup, I was just pointing out that there is more to the poor guy's question
    than just "Do I pick door 1, 2, or 3".

  9. #9
    Danny Kalev Guest

    Re: Returning a reference, pointer or an object

    Actually, what James may have referred to was the the "return value
    optimization" which might work in this case. The problem is that this
    optimization is compiler-dependent and it isn't required by the C++
    standard. Secondly, why rely on compiler's favors? Simply pass a
    reference to a string object and have the function assign a new state to
    that object. This should be the most efficient and probably the safest
    solution.

    Danny

    ralph wrote:
    >
    > "James Curran" <jamescurran@mvps.org> wrote:
    > > True, but irrelevant. Options 2 & 3 have the potential for returning

    > a
    > >reference to a local which is why I avoided them. Option #1 (my choice)
    > >returns an full object. Reference counting merely makes that object
    > >"lighter-weight"
    > >
    > >
    > >--
    > >Truth,
    > >James Curran
    > >www.NovelTheory.com (Personal)
    > >www.NJTheater.com (Professional)
    > >www.aurora-inc.com (Day job)
    > >
    > >
    > >"ralph" <nt_consulting32@hotmail.com> wrote in message
    > >news:3d414d71$1@10.1.10.29...
    > >>
    > >> "James Curran" <jamescurran@mvps.org> wrote:
    > >> > I'd say go with #1 and just accept the (trivial) inefficiency. If

    > >the
    > >> >function is inlined, it may be optimized away anyway, or it could be

    > >negated
    > >> >by a reference counted string class (which the CString in VC6 is -- I'm
    > >> not
    > >> >sure about the CString in VC7).
    > >> >
    > >> >--
    > >> >Truth,
    > >> >James Curran
    > >> >www.NovelTheory.com (Personal)
    > >> >www.NJTheater.com (Professional)
    > >> >www.aurora-inc.com (Day job)
    > >> >
    > >>
    > >> Reference counting won't do much good when returning the address of a

    > >local
    > >> variable.
    > >>

    >
    > Yup, I was just pointing out that there is more to the poor guy's question
    > than just "Do I pick door 1, 2, or 3".


  10. #10
    novice Guest

    Re: Returning a reference, pointer or an object


    There is a discussion about this in one of the Scott Myers' books. Everything
    is clarified there.

    Danny Kalev <dannykk@inter.net.il> wrote:
    >Actually, what James may have referred to was the the "return value
    >optimization" which might work in this case. The problem is that this
    >optimization is compiler-dependent and it isn't required by the C++
    >standard. Secondly, why rely on compiler's favors? Simply pass a
    >reference to a string object and have the function assign a new state to
    >that object. This should be the most efficient and probably the safest
    >solution.
    >
    >Danny
    >
    >ralph wrote:
    >>
    >> "James Curran" <jamescurran@mvps.org> wrote:
    >> > True, but irrelevant. Options 2 & 3 have the potential for returning

    >> a
    >> >reference to a local which is why I avoided them. Option #1 (my choice)
    >> >returns an full object. Reference counting merely makes that object
    >> >"lighter-weight"
    >> >
    >> >
    >> >--
    >> >Truth,
    >> >James Curran
    >> >www.NovelTheory.com (Personal)
    >> >www.NJTheater.com (Professional)
    >> >www.aurora-inc.com (Day job)
    >> >
    >> >
    >> >"ralph" <nt_consulting32@hotmail.com> wrote in message
    >> >news:3d414d71$1@10.1.10.29...
    >> >>
    >> >> "James Curran" <jamescurran@mvps.org> wrote:
    >> >> > I'd say go with #1 and just accept the (trivial) inefficiency.

    If
    >> >the
    >> >> >function is inlined, it may be optimized away anyway, or it could

    be
    >> >negated
    >> >> >by a reference counted string class (which the CString in VC6 is --

    I'm
    >> >> not
    >> >> >sure about the CString in VC7).
    >> >> >
    >> >> >--
    >> >> >Truth,
    >> >> >James Curran
    >> >> >www.NovelTheory.com (Personal)
    >> >> >www.NJTheater.com (Professional)
    >> >> >www.aurora-inc.com (Day job)
    >> >> >
    >> >>
    >> >> Reference counting won't do much good when returning the address of

    a
    >> >local
    >> >> variable.
    >> >>

    >>
    >> Yup, I was just pointing out that there is more to the poor guy's question
    >> than just "Do I pick door 1, 2, or 3".



  11. #11
    Danny Kalev Guest

    Re: Returning a reference, pointer or an object

    Scott discusses it in a very specific context, namely returning a value
    from an overloaded + operator. In that case, you really have no other
    choice but to return the object by value but in the OP's context, a
    reference argument might work better because unlike with overloaded
    operators, you're free to decide how many arguments your function will
    take.

    Danny

    novice wrote:
    >
    > There is a discussion about this in one of the Scott Myers' books. Everything
    > is clarified there.
    >
    > Danny Kalev <dannykk@inter.net.il> wrote:
    > >Actually, what James may have referred to was the the "return value
    > >optimization" which might work in this case. The problem is that this
    > >optimization is compiler-dependent and it isn't required by the C++
    > >standard. Secondly, why rely on compiler's favors? Simply pass a
    > >reference to a string object and have the function assign a new state to
    > >that object. This should be the most efficient and probably the safest
    > >solution.
    > >
    > >Danny
    > >
    > >ralph wrote:
    > >>
    > >> "James Curran" <jamescurran@mvps.org> wrote:
    > >> > True, but irrelevant. Options 2 & 3 have the potential for returning
    > >> a
    > >> >reference to a local which is why I avoided them. Option #1 (my choice)
    > >> >returns an full object. Reference counting merely makes that object
    > >> >"lighter-weight"
    > >> >
    > >> >
    > >> >--
    > >> >Truth,
    > >> >James Curran
    > >> >www.NovelTheory.com (Personal)
    > >> >www.NJTheater.com (Professional)
    > >> >www.aurora-inc.com (Day job)
    > >> >
    > >> >
    > >> >"ralph" <nt_consulting32@hotmail.com> wrote in message
    > >> >news:3d414d71$1@10.1.10.29...
    > >> >>
    > >> >> "James Curran" <jamescurran@mvps.org> wrote:
    > >> >> > I'd say go with #1 and just accept the (trivial) inefficiency.

    > If
    > >> >the
    > >> >> >function is inlined, it may be optimized away anyway, or it could

    > be
    > >> >negated
    > >> >> >by a reference counted string class (which the CString in VC6 is --

    > I'm
    > >> >> not
    > >> >> >sure about the CString in VC7).
    > >> >> >
    > >> >> >--
    > >> >> >Truth,
    > >> >> >James Curran
    > >> >> >www.NovelTheory.com (Personal)
    > >> >> >www.NJTheater.com (Professional)
    > >> >> >www.aurora-inc.com (Day job)
    > >> >> >
    > >> >>
    > >> >> Reference counting won't do much good when returning the address of

    > a
    > >> >local
    > >> >> variable.
    > >> >>
    > >>
    > >> Yup, I was just pointing out that there is more to the poor guy's question
    > >> than just "Do I pick door 1, 2, or 3".


  12. #12
    Peter Friis Guest

    Re: Returning a reference, pointer or an object


    Coming in late to this discussion...

    My favourite method of returning an object which may be expensive to copy:

    std::auto_ptr<T> f(){
    ... // any necessary preparation
    return std::auto_ptr<T>(new T(...));
    }

    Use like this:

    std::auto_ptr<T> t=f();
    t->...
    // result is automatically deleted when t goes out of scope

    or, if you don't need to store the result:

    f()->...
    // result is automatically deleted after execution of above line

    This behaves like a true function (it returns its result rather than modifying
    one of its arguments) but doesn't require the caller to explicitly delete
    the object.


    Peter


  13. #13
    Danny Kalev Guest

    Re: Returning a reference, pointer or an object

    Actually, this is a no-no. The debates over the behavior of auto_ptr
    during the standardization process of C++ changed it from a smart
    pointer to something that I can't even define, but which is never meant
    to be used the way you showed. The problem is that auto_ptr has strict
    ownership semantics. Without going into details (but if you insist,
    please look at this:
    http://gethelp.devx.com/techtips/cpp.../10min1199.asp ), auto_ptr
    should neither be returned from a function nor passed to it by value.
    The problem is that returning it by value causes a copy constructor
    call, which in turn releases the bound object. Consequently, the
    function gets a copy that points to a NULL pointer. Some compilers
    aren't yet standard compliant in this regard (without naming names, you
    know which particular compiler I have in mind). Because of this, you get
    the illusion that your code is valid and works. Well, it isn't. auto_ptr
    is useful only within the scope of declaration.

    BTW, thanks for bringing the subject up:)

    Danny


    Peter Friis wrote:
    >
    > Coming in late to this discussion...
    >
    > My favourite method of returning an object which may be expensive to copy:
    >
    > std::auto_ptr<T> f(){
    > ... // any necessary preparation
    > return std::auto_ptr<T>(new T(...));
    > }
    >
    > Use like this:
    >
    > std::auto_ptr<T> t=f();
    > t->...
    > // result is automatically deleted when t goes out of scope
    >
    > or, if you don't need to store the result:
    >
    > f()->...
    > // result is automatically deleted after execution of above line
    >
    > This behaves like a true function (it returns its result rather than modifying
    > one of its arguments) but doesn't require the caller to explicitly delete
    > the object.
    >
    > Peter


  14. #14
    Peter Friis Guest

    Re: Returning a reference, pointer or an object


    Hi Danny,

    Danny Kalev <dannykk@inter.net.il> wrote:
    >The problem is that auto_ptr has strict
    >ownership semantics. Without going into details (but if you insist,
    >please look at this:
    >http://gethelp.devx.com/techtips/cpp.../10min1199.asp ), auto_ptr
    >should neither be returned from a function nor passed to it by value.


    I read the linked article (which confirmed what I already believed about
    auto_ptr), but it doesn't address the issues of passing an auto_ptr into
    or out of a function.

    >The problem is that returning it by value causes a copy constructor
    >call, which in turn releases the bound object.


    I agree, the auto_ptr is copied, which transfers ownership of the bound object
    from the called function's auto_ptr to the caller's auto_ptr. I thought this
    was what auto_ptr's copy semantics are designed to do.

    >Consequently, the function

    Do you mean the calling or the called function?

    >gets a copy that points to a NULL pointer.

    I don't see how this is so.

    The technique I described is used by Bjarne Stroustrup in his C++ Style and
    Technique FAQ <http://www.research.att.com/~bs/bs_faq2.html> (the second
    example in the section titled "How do I deal with memory leaks?").

    I usually trust Bjarne not to lead me astray with his advice on C++, but
    if I am mistaken this time, I would welcome further guidance.

    >BTW, thanks for bringing the subject up:)


    You're welcome,
    Peter


  15. #15
    DOM1N1CANPOWER Guest

    Re: Returning a reference, pointer or an object


    "ch0rlt0n" <ch0rlt0n@blueyonder.co.uk> wrote:
    >
    >Danny Kalev <dannykk@inter.net.il> wrote:
    >>
    >>
    >>
    >>In C++, if you want to return an object, you have another option: pass
    >>the object by reference as a function argument and have the function
    >>fill it:
    >>
    >> void getDirectory(string &dir)
    >> {
    >> dir = blah;
    >> return dir;
    >> }
    >>
    >>As a rule of thumb, don't return or pass objects by value because of the
    >>incurred performance overhead. Using pointers is a mostly a C thing; in
    >>C++ you should always use references instead of pointers, *unless* a
    >>NULL value is a valid option.
    >>
    >>Danny

    >
    >Sorry Danny, could you clarify whether you intended that function to return
    >a string& or be void and _not_ return anything?
    >
    >Cheers, ch0rlt0n


    Danny u almost right,but remember to return something u must specify what
    u r returning and u can't return something from void,void means no return.


    Directory &Directory::GetDirectory(stirng& dir)
    {
    dir=blah;
    return *this;

    }


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center