473,385 Members | 1,958 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

return a reference


I am trying to clear up some reference questions

if I have a function that returns a reference to an int will that data
be lost when the function goes out of scope
int& retRef()
{
int j=10;

return j;
}

int main()
{

int& k = retRef();

int l = k;

return 0;
}

k is set to 10 after retRef() is called from main, I thought this
would not be possible if retRef() goes out of scope.

Can anyone answer this.

em
Nov 30 '07 #1
8 1573
em******@gmail.com wrote:
I am trying to clear up some reference questions

if I have a function that returns a reference to an int will that data
be lost when the function goes out of scope
int& retRef()
{
int j=10;

return j;
}

int main()
{

int& k = retRef();

int l = k;

return 0;
}

k is set to 10 after retRef() is called from main, I thought this
would not be possible if retRef() goes out of scope.
Any use of the returned reference has *undefined behaviour*, which
includes having what appears to be the actual intended effect. But
it is *undefined* nonetheless, IOW it may or may not even work the
next time run the same program on the same computer.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 30 '07 #2
emannion:
if I have a function that returns a reference to an int will that data
be lost when the function goes out of scope

Off hand, I can only think of four instances in which you'd return a
reference from a function:

1: int &Func() { return my_global_var; }

2: int &Func() { static int i; return i; }

3: int &Func() { return *new int; }

4: int &Func(SomeStruct ss) { return ss.i; }
Case 1 deals with global objects
Case 2 deals with static objects within functions
Case 3 deals with dynamically allocated objects
Case 4 deals with getting an object from the argument somehow

They're the "natural" cases that come to mind. Maybe if I thought about
it hard enough for a while, I could come up with another reason for
returning a reference from a function, but none come to mind instantly.

--
Tomás Ó hÉilidhe
Nov 30 '07 #3
Tomás Ó hÉilidhe wrote:
...
Off hand, I can only think of four instances in which you'd return a
reference from a function:
...
Case 1 deals with global objects
Case 2 deals with static objects within functions
Case 3 deals with dynamically allocated objects
Case 4 deals with getting an object from the argument somehow
...
You forgot the case when it returns a reference to a data member of its
own object. But anyway, trying to enumerate these cases in such a
specific way is a waste of time. The important thing is they all have
the same common property: the object being referenced continues to exist
after the function exits.

--
Best regards,
Andrey Tarasevich
Nov 30 '07 #4
On Nov 30, 8:34 pm, Tomás Ó hÉilidhe <t...@lavabit.comwrote:
4: int &Func(SomeStruct ss) { return ss.i; }
you mean
4: int &Func(SomeStruct& ss) { return ss.i; }
of course.

regards
Kostas
Nov 30 '07 #5
On Nov 30, 11:12 am, kostas <skola...@gmail.comwrote:
On Nov 30, 8:34 pm, Tomás Ó hÉilidhe <t...@lavabit.comwrote:
4: int &Func(SomeStruct ss) { return ss.i; }

you mean
4: int &Func(SomeStruct& ss) { return ss.i; }
of course.
No, no! Tomas is correct; because SomeStruct contains a reference to
an int, and has a trivial copy constructor! ;)

struct SomeStruct
{
int & i;

SomeStruct(int & i_)
:
i(i_)
{}
};

int &Func(SomeStruct ss) { return ss.i; }

#include <iostream>

int main()
{
int i = 42;

SomeStruct ss(i);
int & j = Func(ss);

std::cout << j << '\n';
}

The behavior is well defined. :)

Ali
Nov 30 '07 #6
On Nov 30, 1:42 pm, acehr...@gmail.com wrote:
[...]
std::cout << j << '\n';

}

The behavior is well defined. :)
Actually no! If I'm not mistaken, the standard doesn't define whether
j will be flushed to cout without flushing std::cout (explicitly with
std::flush or possibly implicitly through std::endl). I love C++! :)
Ali
Ali
Nov 30 '07 #7
kostas:
On Nov 30, 8:34 pm, Tomás Ó hÉilidhe <t...@lavabit.comwrote:
>4: int &Func(SomeStruct ss) { return ss.i; }

you mean
4: int &Func(SomeStruct& ss) { return ss.i; } of course.


Nice catch, thanks.

--
Tomás Ó hÉilidhe
Dec 1 '07 #8
em******@gmail.com wrote:
if I have a function that returns a reference to an int will that data
be lost when the function goes out of scope
Not necessarily.
int& retRef()
{
int j=10;

return j;
}
In this case, yes. It's not exactly due to returing a reference, but rather
due to having a reference to an object that is already destroyed. j goes
out of scope as soon as retRef() returns.
int main()
{

int& k = retRef();
At this stage, there is no real error yet. Having a reference to a destroyed
object is ok, but you must not use it, so generally, returing a reference
to a local object makes no sense. However, returing a reference to an
object that lives longer than the function executes would be just fine.
int l = k;
This line invokes undefined behavior by using a reference to an object that
doesn't exist anymore.
return 0;
}

k is set to 10 after retRef() is called from main, I thought this
would not be possible if retRef() goes out of scope.
Well, the behavior is undedfined, which means anything can happen, including
things you don't expect.

Dec 1 '07 #9

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

Similar topics

3
by: Wang Tong | last post by:
Suppose I have a function foo() and a class definition myClass, and I want to create an instance of myClass and return it from foo(). I guess the most efficient way is to return a reference to the...
3
by: Zork | last post by:
Hi, I am a little confused with const functions, for instance (here i am just overloading the unary+ operator) if i define: 1) Length Length :: operator+ ( void ) const {return * this;} ... I...
5
by: klaus triendl | last post by:
hi, recently i discovered a memory leak in our code; after some investigation i could reduce it to the following problem: return objects of functions are handled as temporary objects, hence...
25
by: cppaddict | last post by:
I'd like to know what goes on under the hood when methods return objects. Eg, I have a simple Point class with two members _x and _y. It's constructor, copy constructor, assignment operator and...
14
by: Gama Franco | last post by:
Hi, I'm designing an interface for a shared library, and I would like to know if there is a standard about how to return an object to the user. I will use exceptions to report errors, so there...
5
by: Neal Coombes | last post by:
Posted to comp.lang.c++.moderated with little response. Hoping for better from the unmoderated groups: -------- Original Message -------- Subject: Return appropriately by value, (smart)...
12
by: Jose Fernandez | last post by:
Hello. I'm building a web service and I get this error. NEWS.News.CoverNews(string)': not all code paths return a value This is the WebMethod public SqlDataReader CoverNews(string Sport)...
20
by: weston | last post by:
I've got a piece of code where, for all the world, it looks like this fails in IE 6: hometab = document.getElementById('hometab'); but this succeeds: hometabemt =...
2
by: Eric Lilja | last post by:
Hello, consider this complete program: #include <iostream> #include <string> using std::cout; using std::endl; using std::string; class Hanna {
12
by: huangshan | last post by:
hi all In what condition i need( or mast) a (templates)function return value by reference? can you give me a example thanks
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.