473,581 Members | 3,046 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning by value, returning by reference

When I compile and run the following on my system:
#include <iostream>

static int hello = 78;
int ReturnValue(voi d)
{
return hello;
}
int& ReturnRef(void)
{
return hello;
}
int main(void)
{
const int& value = ReturnValue();

const int& ref = ReturnRef();

if ( &value == &ref )
{
std::cout << "They're the same!!" << std::endl;
}
else
{
std::cout << "They're different!!" << std::endl;
}

std::system("pa use");

}
, it prints "They're different". I'm curious as to why?!
I was thinking along these lines at first:

You can bind a temporary returned from a function to a reference. Therefore,
it's just the same as the function returning by reference, except that it's
const.

As such, I expected the output to be "They're the same!!".
Any thoughts?
-JKop
Jul 22 '05 #1
19 1953
JKop posted:
When I compile and run the following on my system:
#include <iostream>

static int hello = 78;
int ReturnValue(voi d)
{
return hello;
}
int& ReturnRef(void)
{
return hello;
}
int main(void)
{
const int& value = ReturnValue();

const int& ref = ReturnRef();

if ( &value == &ref )
{
std::cout << "They're the same!!" << std::endl;
}
else
{
std::cout << "They're different!!" << std::endl;
}

std::system("pa use");

}
, it prints "They're different". I'm curious as to why?!
I was thinking along these lines at first:

You can bind a temporary returned from a function to a reference.
Therefore, it's just the same as the function returning by reference,
except that it's const.

As such, I expected the output to be "They're the same!!".
Any thoughts?
-JKop

Another thought:

A function that returns a const reference.
A function that returns by value.
int Monkey(void)
{
int monkey = 72;

return monkey;
}
const int& Ape(void)
{
int ape = 72;

return ape;
}
They're exactly the same, right? There shouldn't be any difference, eg. an
extra temporary made.
-JKop
Jul 22 '05 #2
"JKop" <NU**@NULL.NULL > wrote in message
news:6q******** *********@news. indigo.ie...
....
const int& value = ReturnValue(); .... You can bind a temporary returned from a function to a reference. Therefore, it's just the same as the function returning by reference, except that it's const.

Not the same actually.
The story is more like: the function returned the copy of a value,
eventually stored on the stack. By using a const reference, we are
trying to tell the compiler to avoid copying the value again into
a local variable, and to extend the lifetime of the temporary it
stores a reference to.

The original variable whose copy was returned by "ReturnValu e()"
is never accessible from the outside.
hth
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- e-mail contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Jul 22 '05 #3
JKop wrote in news:6q******** *********@news. indigo.ie in comp.lang.c++:
When I compile and run the following on my system:
#include <iostream>

static int hello = 78;
int ReturnValue(voi d)
{
This Function returns a *copy* of 'hello'.
return hello;
}
int& ReturnRef(void)
{
return hello;
}
int main(void)
{
const int& value = ReturnValue();
In the above the compiler creates a temporary in which it stores
a the value returned by ReturnValue. In effect something like:

int temp = ReturnValue();
int const &value = temp;

const int& ref = ReturnRef();

if ( &value == &ref )
{
std::cout << "They're the same!!" << std::endl;
}
else
{
std::cout << "They're different!!" << std::endl;
}

std::system("pa use");

}
, it prints "They're different". I'm curious as to why?!
I was thinking along these lines at first:

You can bind a temporary returned from a function to a reference.
This is true, but you conclusion doesen't follow.
Therefore, it's just the same as the function returning by reference,
except that it's const.

Binding temporaries to constant references *isn't* a result
of the way temoraries are created, it happens because the
standard says so, there is hence no "Therefore" .
As such, I expected the output to be "They're the same!!".
Any thoughts?


Logic applies to why the language is the way it is, but that
doesn't mean the language is (always) logical.

If you haven't got one already get a good book.
If you haven't got it already get a copy of the C++ Standard.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #4
JKop wrote in news:5u******** *********@news. indigo.ie in comp.lang.c++:

A function that returns a const reference.
A function that returns by value.
This is OK.
int Monkey(void)
{
int monkey = 72;

return monkey;
}

This is UB (it maybe diagnostic (i.e. warning) required).

const int& Ape(void)
{
int ape = 72;

return ape;
'ape' has now been destroyed, the returned reference, referes
to an object that no longer exists.

}
They're exactly the same, right? There shouldn't be any difference,
eg. an extra temporary made.


No.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #5
Rob Williscroft posted:
Therefore, it's just the same as the function returning by reference,
except that it's const.


Binding temporaries to constant references *isn't* a result
of the way temoraries are created, it happens because the
standard says so, there is hence no "Therefore" .


I'll make myself more clear:
int monkey(void);

const int& ape(void);
I wasn't talking about how you've to:

const int& primate = monkey;
-JKop
Jul 22 '05 #6

int monkey = ReturnIntValue( );

const int& monkey = ReturnIntValue( );
I once heard an argument that the binding-to-a-reference one is better
because it avoids an extra temporary. If this is so, why the hell doesn't
the following print "They're the same!!"?:

#include <iostream>

const int* g_p1;

const int* g_p2;
int Chocolate(void)
{
int monkey = 42;

g_p1 = &monkey;
return monkey;
}
int main(void)
{
const int& cream = Chocolate();

g_p2 = &cream;

if (g_p1 == g_p2)
{
std::cout << "They're the same!!";
}
{
std::cout << "They're different!!";
}

std::system("pa use");

}
-JKop

Jul 22 '05 #7
JKop wrote in news:JK******** *********@news. indigo.ie in comp.lang.c++:
Rob Williscroft posted:
Therefore, it's just the same as the function returning by reference,
except that it's const.


Binding temporaries to constant references *isn't* a result
of the way temoraries are created, it happens because the
standard says so, there is hence no "Therefore" .


I'll make myself more clear:
int monkey(void);

const int& ape(void);
I wasn't talking about how you've to:

const int& primate = monkey;


That *isn't* clearer in any way.
Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #8
Rob Williscroft posted:
JKop wrote in news:5u******** *********@news. indigo.ie in comp.lang.c++:

A function that returns a const reference.
A function that returns by value.

This is OK.

int Monkey(void)
{
int monkey = 72;

return monkey; }


This is UB (it maybe diagnostic (i.e. warning) required).


What does UB stand for?

While I'm asking, what does OP stand for?


const int& Ape(void)
{
int ape = 72;

return ape;


'ape' has now been destroyed, the returned reference, referes
to an object that no longer exists.

When you return by value, the object exists until the next ;. When you
return by reference, the object is destroy immediately. Is that what you're
saying? ie.

int ReturnIntValue( void);

const int& ReturnIntRef(vo id);

void TakesInt(const int);
int main(void)
{
TakesInt( ReturnIntValue( ) );

//Nothing wrong because the object exists until the next ;

TakesInt( ReturnIntRef() );

//This is undefined behaviour because the object was destroyed
//immediately

}
I don't know why I'm asking the following question, but still absolute
clarity would be nice:

const int ReturnValue(voi d);
int ReturnValue(voi d);
They're exactly the same, right? (Yes, I realize how stupid the question
sounds!)

-JKop
Jul 22 '05 #9
Rob Williscroft posted:
JKop wrote in news:JK******** *********@news. indigo.ie in comp.lang.c++:
Rob Williscroft posted:
Therefore, it's just the same as the function returning by reference,
except that it's const.
Binding temporaries to constant references *isn't* a result
of the way temoraries are created, it happens because the
standard says so, there is hence no "Therefore" .


I'll make myself more clear:
int monkey(void);

const int& ape(void);
I wasn't talking about how you've to:

const int& primate = monkey;


That *isn't* clearer in any way.
Rob.


Anyway, this has been addressed elsewhere in the thread.

END

-JKop
Jul 22 '05 #10

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

Similar topics

6
14011
by: Krackers | last post by:
How do you write a function which returns a reference to an array. I can only get a function to return a copy of the array itself. I've had a look at some other threads in this group an the return value of a function acts like 'by Val' returning the value only (except for objects) can you make it return a reference instead? cheers, Krackers
9
11901
by: mjm | last post by:
Folks, Stroustrup indicates that returning by value can be faster than returning by reference but gives no details as to the size of the returned object up to which this holds. My question is up to which size m would you expect vector<double> returns_by_value() {
4
1764
by: Patrick | last post by:
I want to achieve the following behaviour but I am having trouble getting there...bare with me im knew to c++ , so its probably rather trivial! To have a class ClassA, and composed within this class is an instance of another class, ClassB. I want to have a method getClassB that returns a reference to the instance of ClassB composed within...
18
2125
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>
11
1927
by: JKop | last post by:
AnyClass Blah() { AnyClass poo; return poo; } As we all know, in the above, the compiler is entitled to:
25
2915
by: Victor Bazarov | last post by:
In the project I'm maintaining I've seen two distinct techniques used for returning an object from a function. One is AType function(AType const& arg) { AType retval(arg); // or default construction and then.. // some other processing and/or changing 'retval' return retval; }
13
4499
by: Matthias Kaeppler | last post by:
Hi, I was wondering why library implementors often make getter functions return strings by value (copies). For example, in boost::filesystem the leaf() function returns an std::string by value. So does Gnome::Vfs::FileInfo::get_name(). Isn't that unnecessary overhead? I could as well return by reference to const-string and avoid
23
2922
by: pauldepstein | last post by:
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
8
2205
by: darren | last post by:
Hi everybody, have a quick look at this code: ===== ===== int main(void) { string msg; makeString(msg); cout << "back in main, result = " << msg << endl;
0
7886
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7809
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
8159
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7920
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8183
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...
0
5366
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3809
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...
1
2312
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
0
1147
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.