473,561 Members | 3,118 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

returning references

Below is posted from a link for Stanford students in computer
science.

QUOTE BEGINS HERE
Because of the risk of misuse, some experts recommend never returning
a
reference from a function or method.
QUOTE ENDS HERE

I have never heard anyone else say that it is a problem for a function
to return a reference. Are there really experts who object, or is
this nothing other than the commonplace observation that reference-
returning is a somewhat difficult concept that needs to be learned
carefully? (I am just learning about this now.) Assuming programmers
have some degree of competence and are able to avoid returning
references to locals and so on, what (if anything) are the pitfalls?

Paul Epstein
Jan 4 '08 #1
23 2911
On Jan 3, 6:26 pm, pauldepst...@at t.net wrote:
Below is posted from a link for Stanford students in computer
science.

QUOTE BEGINS HERE
Because of the risk of misuse, some experts recommend never returning
a
reference from a function or method.
QUOTE ENDS HERE

I have never heard anyone else say that it is a problem for a function
to return a reference. Are there really experts who object, or is
this nothing other than the commonplace observation that reference-
returning is a somewhat difficult concept that needs to be learned
carefully? (I am just learning about this now.) Assuming programmers
have some degree of competence and are able to avoid returning
references to locals and so on, what (if anything) are the pitfalls?

Paul Epstein
I don't see anything at all with returning references as long as the
const keyword is used correctly when appropriate. Surprisingly, a good
number of people do not use const when creating thier function stubs;

const MyClass & GetMyClass() const; // The typical accessor
SetMyClass(cons t MyClass & myclass); // The typical mutator

I constantly find the above two methods lacking the const keyword in
source when I am debugging and it leads to misuse by other programmers
who simply glance at a method without taking into account the impact
of making changes to the returned reference.

Another common problem I run into is you can't return NULL for a
reference. Sometimes it is nice to have the option to return NULL when
an error occured in which case I use a pointer and tell the caller to
check the returned value to determine if an error occured. Some people
don't like that idea though, but it is worth mentioning.
Jan 4 '08 #2
On 2008-01-04 01:26, pa**********@at t.net wrote:
Below is posted from a link for Stanford students in computer
science.

QUOTE BEGINS HERE
Because of the risk of misuse, some experts recommend never returning
a
reference from a function or method.
QUOTE ENDS HERE

I have never heard anyone else say that it is a problem for a function
to return a reference. Are there really experts who object, or is
this nothing other than the commonplace observation that reference-
returning is a somewhat difficult concept that needs to be learned
carefully? (I am just learning about this now.) Assuming programmers
have some degree of competence and are able to avoid returning
references to locals and so on, what (if anything) are the pitfalls?
As far as I know there is only one pitfall, and that is returning a
reference to a variable local to the function, like so:

int& foo(int i)
{
int r = i+i;
return r;
}

int main()
{
int& twice = foo(5);
}

Since r is a local variable to foo() it will go out of scope as soon as
foo() is done executing, this means that the reference returned refers
to a variable that no longer exists.

On the other hand there are a number of valid reasons to return a
reference from a function, a function that returns an element from a
collection is a good example (look at the at() function in std::vector).

--
Erik Wikström
Jan 4 '08 #3
On Jan 4, 12:26*am, pauldepst...@at t.net wrote:
Below is posted from a link for Stanford students in computer
science.

QUOTE BEGINS HERE
Because of the risk of misuse, some experts recommend never returning
a
reference from a function or method.
QUOTE ENDS HERE
hmmm... I assume that following this extremely wise and useful advice,
Stanford students will not be allowed to do ...

#include <iostream>
int main(){
std::cout << "hello world\n";
}
regards
Andy Little

(Thankfully Not a C++ expert!) :-)
Jan 4 '08 #4
pa**********@at t.net wrote:
Below is posted from a link for Stanford students in computer
science.

QUOTE BEGINS HERE
Because of the risk of misuse, some experts recommend never
returning a reference from a function or method.
QUOTE ENDS HERE

I have never heard anyone else say that it is a problem for a
function to return a reference.
"C++ Coding Standards" by Sutter & Alexandrescu. Item 42: Don't give
away your internals.

Don't volunteer too much: Avoid returning handles to internal data
managed by your class, so clients won't uncontrollably modify
state that your object thinks it owns.

For context, "handles" above is defined as non-const references, and
pointers to non-const data.

So now you have heard of at least two acknowledged experts who almost
state the same thing.
Are there really experts who object, or is this nothing other than
the commonplace observation that reference- returning is a somewhat
difficult concept that needs to be learned carefully? (I am just
learning about this now.) Assuming programmers have some degree of
competence and are able to avoid returning references to locals and
so on, what (if anything) are the pitfalls?
The only valid reference that can be returned from a non-member function
is something that either the calling code had access to anyway, or
something that is buried in a module.

The only valid reference that can be returned from a member-function is
of something that either the calling code had access to anyway, or
something that is private within the class.

In either case, if you are returning a non-const reference, then the
object returned better not have anything to do with the invariant of
that class/module or the class/module is asking for trouble
(encapsulation is broken.)
Jan 4 '08 #5
On Jan 3, 11:14 pm, "Daniel T." <danie...@earth link.netwrote:
pauldepst...@at t.net wrote:
Below is posted from a link for Stanford students in computer
science.
QUOTE BEGINS HERE
Because of the risk of misuse, some experts recommend never
returning a reference from a function or method.
QUOTE ENDS HERE
I have never heard anyone else say that it is a problem for a
function to return a reference.

"C++ Coding Standards" by Sutter & Alexandrescu. Item 42: Don't give
away your internals.

Don't volunteer too much: Avoid returning handles to internal data
managed by your class, so clients won't uncontrollably modify
state that your object thinks it owns.

For context, "handles" above is defined as non-const references, and
pointers to non-const data.

So now you have heard of at least two acknowledged experts who almost
state the same thing.
I beg to differ with the statement that two quotes from so called
experts _almost_ say the same thing. They are extremely different
considering the impact of const correctness. the former quote is
moronic and the latter is imo quite correct.

Are there really experts who object, or is this nothing other than
the commonplace observation that reference- returning is a somewhat
difficult concept that needs to be learned carefully? (I am just
learning about this now.) Assuming programmers have some degree of
competence and are able to avoid returning references to locals and
so on, what (if anything) are the pitfalls?

The only valid reference that can be returned from a non-member function
is something that either the calling code had access to anyway, or
something that is buried in a module.

The only valid reference that can be returned from a member-function is
of something that either the calling code had access to anyway, or
something that is private within the class.
What's stopping me from returning a reference to protected data
exactly?
In either case, if you are returning a non-const reference, then the
object returned better not have anything to do with the invariant of
that class/module or the class/module is asking for trouble
(encapsulation is broken.)
agreed.
Jan 4 '08 #6
On Jan 3, 7:26 pm, pauldepst...@at t.net wrote:
Below is posted from a link for Stanford students in computer
science.

QUOTE BEGINS HERE
Because of the risk of misuse, some experts recommend never returning
a
reference from a function or method.
QUOTE ENDS HERE

I have never heard anyone else say that it is a problem for a function
to return a reference. Are there really experts who object, or is
this nothing other than the commonplace observation that reference-
returning is a somewhat difficult concept that needs to be learned
carefully? (I am just learning about this now.) Assuming programmers
have some degree of competence and are able to avoid returning
references to locals and so on, what (if anything) are the pitfalls?

Paul Epstein
Nothing wrong in returning references, example: various operators.
You already coverred the case of returning a temporary.
One pitfall is side-effects where an accessor might _get_ nasty.
Thats where CV-qualifiers play an important role.

#include <iostream>
#include <ostream>

class N
{
int m_n;
public:
N(int n) : m_n(n) { }
// accessors
int& getnasty() { return m_n; } // nasty
int const& getsafe() const { return m_n; }
void set(const int& n) { m_n = n; }
// friend op<<
friend std::ostream&
operator<<(std: :ostream& os, const N& r)
{
return os << r.m_n;
}
};

int main()
{
N instance(9);
std::cout << instance << std::endl;

instance.getnas ty() = -1; // nasty side-effect
std::cout << instance << std::endl;

instance.set(8) ;
std::cout << instance << std::endl;
std::cout << instance.getsaf e() << std::endl;
}

/*
9
-1
8
8
*/
Jan 4 '08 #7
kwikius wrote:
On Jan 4, 12:26 am, pauldepst...@at t.net wrote:
>Below is posted from a link for Stanford students in computer
science.

QUOTE BEGINS HERE
Because of the risk of misuse, some experts recommend never returning
a
reference from a function or method.
QUOTE ENDS HERE

hmmm... I assume that following this extremely wise and useful advice,
Stanford students will not be allowed to do ...

#include <iostream>
int main(){
std::cout << "hello world\n";
well this is allowed, while
std::cout << "hello world" << std::endl;
is not,

write
std::cout << "hello world";
std::cout << std::endl;
instead.

:D
}
regards
Andy Little

(Thankfully Not a C++ expert!) :-)
Jan 4 '08 #8
On Jan 4, 6:48 am, Christopher <cp...@austin.r r.comwrote:
On Jan 3, 11:14 pm, "Daniel T." <danie...@earth link.netwrote:
pauldepst...@at t.net wrote:
Below is posted from a link for Stanford students in computer
science.
QUOTE BEGINS HERE
Because of the risk of misuse, some experts recommend never
returning a reference from a function or method.
QUOTE ENDS HERE
I have never heard anyone else say that it is a problem for a
function to return a reference.
"C++ Coding Standards" by Sutter & Alexandrescu. Item 42: Don't give
away your internals.
Don't volunteer too much: Avoid returning handles to internal data
managed by your class, so clients won't uncontrollably modify
state that your object thinks it owns.
For context, "handles" above is defined as non-const references, and
pointers to non-const data.
So now you have heard of at least two acknowledged experts who almost
state the same thing.
I beg to differ with the statement that two quotes from so called
experts _almost_ say the same thing. They are extremely different
considering the impact of const correctness. the former quote is
moronic and the latter is imo quite correct.
The real difference is that they are addressing two radically
different levels. The Sutter/Alexandrescu quote has nothing to
do with references per se, but is more concerned with design;
I'm sure that neither Sutter nor Alexandrescu would condemn
std::vector<>:: operator[] because it returns a reference (to
internal data, no less), nor the operator<< and operator>in
iostream because they return a reference to support chaining.
(Alexandrescu definitly doesn't like iostream, but I don't think
that the fact that operator<< returns a reference has anything
to do with it.)

The real difference is that Sutter and Alexandrescu address a
real issue with their comment: how to intelligently design a
class. Where as the quoted recommendation simply misses the
point entirely, by concentrating on an irrelevant syntax issue.
(How is returning a reference riskier than returning a pointer,
for example?)
Are there really experts who object, or is this nothing
other than the commonplace observation that reference-
returning is a somewhat difficult concept that needs to be
learned carefully? (I am just learning about this now.)
Assuming programmers have some degree of competence and
are able to avoid returning references to locals and so
on, what (if anything) are the pitfalls?
The only valid reference that can be returned from a
non-member function is something that either the calling
code had access to anyway, or something that is buried in a
module.
The only valid reference that can be returned from a
member-function is of something that either the calling code
had access to anyway, or something that is private within
the class.
What's stopping me from returning a reference to protected
data exactly?
In either case, if you are returning a non-const reference,
then the object returned better not have anything to do with
the invariant of that class/module or the class/module is
asking for trouble (encapsulation is broken.)
agreed.
But what does that say, anyway? And how is returning a
reference any more of a problem here than returning a pointer.

There are two issues with returning a reference; permitting
access to internal details, and the lifetime of what is referred
to. They're both design issues, both affect other constructs as
well, and neither affects all use of references. Many standard
idioms and patterns involve returning references, and I've never
heard of any expert who recommended never returning a reference.

--
James Kanze (GABI Software) mailto:ja****** ***@gmail.com
Conseils en informatique orient�e objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place S�mard, 78210 St.-Cyr-l'�cole, France, +33 (0)1 30 23 00 34
Jan 4 '08 #9
On 2008-01-04 10:29, Barry wrote:
kwikius wrote:
>On Jan 4, 12:26 am, pauldepst...@at t.net wrote:
>>Below is posted from a link for Stanford students in computer
science.

QUOTE BEGINS HERE
Because of the risk of misuse, some experts recommend never returning
a
reference from a function or method.
QUOTE ENDS HERE

hmmm... I assume that following this extremely wise and useful advice,
Stanford students will not be allowed to do ...

#include <iostream>
int main(){
std::cout << "hello world\n";

well this is allowed, while
std::cout << "hello world" << std::endl;
is not,

write
std::cout << "hello world";
std::cout << std::endl;
instead.
The reference will be returned regardless if you use it or not, but I
guess they make an exception for library functions :-)

PS. Please do not quote signatures

--
Erik Wikström
Jan 4 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1896
by: Justin Koivisto | last post by:
I was wondering if there was a way to return a reference of an object that lies within another object... <?php class my_class_1{ var $_db=NULL; function my_class_1(){ $this->_db=new my_class_2(TRUE); return TRUE;
1
7419
by: Andrew Fleet | last post by:
Hi, I'm looking at returning a reference to an array I create within a subroutine. I could do this... sub foo { my @theArray; <snip>
7
20338
by: Pablo J Royo | last post by:
Hello: i have a function that reads a file as an argument and returns a reference to an object that contains some information obtained from the file: FData &ReadFile(string FilePath); But , for example, when the file doesnt exists, i should not return any reference to a bad constructed object, so i need something as a NULL reference...
18
2120
by: cppaddict | last post by:
Hi, Is it considered bad form to have the subscript operator return a const reference variable? If not, what is the proper way to do it? My question was prompted by the code below, my problematic attempt to implement a subscript operator that returns a const reference. The dubious code is marked at the end. <code>
12
3264
by: Olumide | last post by:
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is an absolutely fantastic book; however on page 175 (topic: operator overlaoding), there the following code snippet: inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global function { MFVec res = z1; res += z2 return res; // WHY???
2
1673
by: matthias_k | last post by:
Hello, I'm wondering if returning const references to a class member is generally faster than returning a copy of the object. Consider this code: class A { std::string data; public:
10
10270
by: Fraser Ross | last post by:
I need to know the syntax for writing a reference of an array. I haven't seen it done often. I have a class with a member array and I want a member function to return an reference to it. Returning a pointer to the first element might do but I want to do what I've said. Fraser.
3
4300
by: Alfonso Morra | last post by:
I'm in the process of implementing an abstract factory design pattern for an application. I would like to know, which is the recommended way of returning objects from the factory - by reference or by pointer? Returning pointers is a no brainer, but I'm not sure how to return a reference to a newly created object, in a method call. (Yes, I...
6
1973
by: Derrick | last post by:
Hello all; Since I do have working code, this is more for my curiosity only. I'm creating a "Plugin" architecture, following some of the many examples on the 'net. Basically what I have is this: - a DLL which contains the interface that every plugin must implement (IPlugin). This DLL also contains a class with the ability to search for...
0
7637
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main...
0
7558
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8072
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7924
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5462
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3609
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3591
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2055
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1171
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.