473,385 Members | 1,256 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.

Assign return value to reference

Hi,

I'm trying to figure out if the following code is correct or could cause problems in some way...

class MyClass {
...
};

MyClass doSomething() {
...
MyClass obj;
....
return obj;
}

int main() {
MyClass &ret = doSomething();
...
return 0;
}

So function doSomething() returns an object, and "ret" is referring to that object. The question is now whether "ret" refers to a valid object or not?

--
Knut Stolze
Data Warehousing for DB2 z/OS
IBM Germany Research & Development
Aug 19 '08 #1
6 2465
Knut Stolze wrote:
Hi,

I'm trying to figure out if the following code is correct or could cause problems in some way...

class MyClass {
...
};

MyClass doSomething() {
...
MyClass obj;
....
return obj;
}

int main() {
MyClass &ret = doSomething();
...
return 0;
}

So function doSomething() returns an object, and "ret" is referring to that object. The question is now whether "ret" refers to a valid object or not?
Your example doesnt compile. However, I tried to compile this:
class MyClass {
};
MyClass doSomething() {
MyClass obj;
return obj;
}
int main() {
MyClass &ret = doSomething();
return 0;
}

with gcc without any additional options, and I got :
o1.cpp: In function ‘int main()’:
o1.cpp:10: error: invalid initialization of non-const reference of type
‘MyClass&’ from a temporary of type ‘MyClass’
btw don't forget to take a look at this:
http://www.parashift.com/c++-faq-lit...t.html#faq-5.8
Aug 19 '08 #2
On 19 ago, 09:13, Knut Stolze <sto...@de.ibm.comwrote:
Hi,

I'm trying to figure out if the following code is correct or could cause problems in some way...

class MyClass {
* * ...

};

MyClass doSomething() {
* * ...
* * MyClass obj;
* * ....
* * return obj;

}

int main() {
* * MyClass &ret = doSomething();
* * ...
* * return 0;

}

So function doSomething() returns an object, and "ret" is referring to that object. *The question is now whether "ret" refers to a valid object ornot?
Hi.

It does not. In fact, it should give you a compiler error (or at least
a warning) because the return of doSomething is temporary. Using a
const-ref in this case is allowed because the life-time of the copy
will be extended.

int main()
{
const MyClass &ret = doSomething(); //Notice the const.
...
return 0;
}

--
Leandro T. C. Melo
Aug 19 '08 #3
Leandro Melo wrote:
On 19 ago, 09:13, Knut Stolze <sto...@de.ibm.comwrote:
>Hi,

I'm trying to figure out if the following code is correct or could cause
problems in some way...

class MyClass {
...

};

MyClass doSomething() {
...
MyClass obj;
....
return obj;

}

int main() {
MyClass &ret = doSomething();
...
return 0;

}

So function doSomething() returns an object, and "ret" is referring to
that object. The question is now whether "ret" refers to a valid object
or not?

Hi.

It does not. In fact, it should give you a compiler error (or at least
a warning) because the return of doSomething is temporary. Using a
const-ref in this case is allowed because the life-time of the copy
will be extended.

int main()
{
const MyClass &ret = doSomething(); //Notice the const.
...
return 0;
}
Sorry, my fault. I should have written a short program to demonstrate the issue.

Where can I find the details (in the C++ standard) on the life-time extension of the temporary copy?

--
Knut Stolze
Data Warehousing for DB2 z/OS
IBM Germany Research & Development
Aug 19 '08 #4
Leandro Melo wrote:
const MyClass &ret = doSomething(); //Notice the const.
AFAIK, in practice there's absolutely no difference between that line
and this one:

const MyClass ret = doSomething();

I could even guess most compilers will probably generate the exact
same machine code from both (although some compilers might not, ie. they
might allocate the object at different parts depending on the situation,
but the effect will nevertheless be exactly the same).
Aug 19 '08 #5
On 19 ago, 12:17, Juha Nieminen <nos...@thanks.invalidwrote:
Leandro Melo wrote:
* * *const MyClass &ret = doSomething(); //Notice the const.

* AFAIK, in practice there's absolutely no difference between that line
and this one:

* * *const MyClass ret = doSomething();

* I could even guess most compilers will probably generate the exact
same machine code from both (although some compilers might not, ie. they
might allocate the object at different parts depending on the situation,
but the effect will nevertheless be exactly the same).

So could I ;) For this particular case it will probably not make a
difference from a practical point of view. But I wanted to show that
const refs can be used to extend the life-time of temporary objects,
which can be useful in other situations.

--
Leandro T. C. Melo
Aug 19 '08 #6
Juha Nieminen schrieb:
Leandro Melo wrote:
> const MyClass &ret = doSomething(); //Notice the const.

AFAIK, in practice there's absolutely no difference between that line
and this one:

const MyClass ret = doSomething();

I could even guess most compilers will probably generate the exact
same machine code from both (although some compilers might not, ie. they
might allocate the object at different parts depending on the situation,
but the effect will nevertheless be exactly the same).
It might generate the same machine code in this case, but if you don't
use a reference and you have a different type for the local variable
than the return type, the return value gets sliced.

Example:

class Base {};
class MyClass : public Base {};
MyClass doSomething() {
return MyClass();
}
int main() {
const Base base1 = doSomething();
const Base &base2 = doSomething();
return 0;
}

base1 actually *is* a Base, base2 references an object of type MyClass.

--
Thomas
Aug 20 '08 #7

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

Similar topics

25
by: Rim | last post by:
Hi, I have been thinking about how to overload the assign operation '='. In many cases, I wanted to provide users of my packages a natural interface to the extended built-in types I created for...
4
by: Eric | last post by:
How can I dynamically assign an event to an element? I have tried : (myelement is a text input) document.getElementById('myelement').onKeyUp = "myfnc(param1,param2,param3)"; ...
9
by: ckerns | last post by:
I want to loop thru an array of controls,(39 of them...defaults = 0). If value is null or non-numeric I want to assign the value of "0". rowString = "L411" //conrol name if (isNaN(eval...
10
by: John | last post by:
Ok. I'm not sure whether this is cool or perverted, I need second opinion ;) I define two classes as follows: /********************************************/ public sealed class Dummy {...
2
by: **Developer** | last post by:
I do the following: Note that I'm returning and interface because GetDatObject returns an interface. Public Shared Function GetContents() As DataObject Dim ClipboardDataO As IDataObject =...
7
by: Edward Diener | last post by:
Since implement the assign operator for reference types eliminates the ability to assign a reference object to a reference variable of the same type or base class of that type, I assume that...
4
by: Learner | last post by:
Hello, This my a method to call a stored proce and uses a DataReader to read the data in the below method I am trying to assign a null value to my datareader variable Dim datareader As...
12
by: Danny Colligan | last post by:
In the following code snippet, I attempt to assign 10 to every index in the list a and fail because when I try to assign number to 10, number is a deep copy of the ith index (is this statement...
18
by: joaotsetsemoita | last post by:
Hello everyone, I'm having troubles assigning an onclick event to a cell. Im trying something like cursorPoint.cells.style.cursor = "hand"; cursorPoint.cells.width = "20";...
5
by: howa | last post by:
Hi, Consider a simple example, e.g. var a = { 'a': 'b', 'c': 'd' }
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: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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: 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.