473,568 Members | 2,820 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

const reference to object returned by value

Hi,

I'm looking at the differences between:

const NonTrivialObjec t& obj =
functionThatRet urnsANonTrivial ObjectByValue() ;

and:

const NonTrivialObjec t obj =
functionThatRet urnsANonTrivial ObjectByValue() ;

My question is, can I expect these two lines to be any different?

I assumed that the object returned by the function becomes a
temporary. In the first line, I thought that the const reference
would be bound to that temporary, causing the temporary to hang around
until the reference dies.

In the second line, I assumed that the temporary returned from the
function is then copied into 'obj'. Hence, the first line saves a
copy. My testing has proven this completely wrong. See the following
code and results. Is there anything in the standard that could
clarify this, or is this completely compiler-specific?

The code below compiled in gcc 3.4.4 outputs:
Start.
Copy!
A
B
C
Copy!
D
E
F

Microsoft CL 14.00.5 (from VS 8.0) outputs:
Start.
Copy!
A
B
Copy!
C
Copy!
D
E
Copy!
F

Code:

#include <iostream>
class testClass {
public:
testClass() { }

testClass(const testClass& t) { std::cerr << "Copy!\n"; }
};

class ObjectFactory {
public:
ObjectFactory() { }
testClass getResidentObje ct() const {
return m_object;
}

testClass getLocalTempObj ect() {
return testClass();
}

testClass getLocalObject( ) {
testClass t;
return t;
}

private:
testClass m_object;
};

int main() {
ObjectFactory of;
std::cerr << "Start.\n";

const testClass& t1 = of.getResidentO bject();
std::cerr << "A\n";

const testClass& t2 = of.getLocalTemp Object();
std::cerr << "B\n";

const testClass& t3 = of.getLocalObje ct();
std::cerr << "C\n";

const testClass t4 = of.getResidentO bject();
std::cerr << "D\n";

const testClass t5 = of.getLocalTemp Object();
std::cerr << "E\n";

const testClass t6 = of.getLocalObje ct();
std::cerr << "F\n";

return 0;
}

Any insight would be appreciated. Basically, I'm trying to decide if
it's ever worth using a const reference to refer to something returned
from a function.

Ryan

Aug 29 '07 #1
3 1805
On Aug 29, 1:57 pm, rwf_20 <rfr...@gmail.c omwrote:
Hi,

I'm looking at the differences between:

const NonTrivialObjec t& obj =
functionThatRet urnsANonTrivial ObjectByValue() ;

and:

const NonTrivialObjec t obj =
functionThatRet urnsANonTrivial ObjectByValue() ;

My question is, can I expect these two lines to be any different?

I assumed that the object returned by the function becomes a
temporary. In the first line, I thought that the const reference
would be bound to that temporary, causing the temporary to hang around
until the reference dies.

In the second line, I assumed that the temporary returned from the
function is then copied into 'obj'. Hence, the first line saves a
copy. My testing has proven this completely wrong. See the following
code and results. Is there anything in the standard that could
clarify this, or is this completely compiler-specific?

The code below compiled in gcc 3.4.4 outputs:
Start.
Copy!
A
B
C
Copy!
D
E
F

Microsoft CL 14.00.5 (from VS 8.0) outputs:
Start.
Copy!
A
B
Copy!
C
Copy!
D
E
Copy!
F

Code:

#include <iostream>
class testClass {
public:
testClass() { }

testClass(const testClass& t) { std::cerr << "Copy!\n"; }

};

class ObjectFactory {
public:
ObjectFactory() { }
testClass getResidentObje ct() const {
return m_object;
}

testClass getLocalTempObj ect() {
return testClass();
}

testClass getLocalObject( ) {
testClass t;
return t;
}

private:
testClass m_object;

};

int main() {
ObjectFactory of;
std::cerr << "Start.\n";

const testClass& t1 = of.getResidentO bject();
std::cerr << "A\n";

const testClass& t2 = of.getLocalTemp Object();
std::cerr << "B\n";

const testClass& t3 = of.getLocalObje ct();
std::cerr << "C\n";

const testClass t4 = of.getResidentO bject();
std::cerr << "D\n";

const testClass t5 = of.getLocalTemp Object();
std::cerr << "E\n";

const testClass t6 = of.getLocalObje ct();
std::cerr << "F\n";

return 0;

}

Any insight would be appreciated. Basically, I'm trying to decide if
it's ever worth using a const reference to refer to something returned
from a function.

Ryan
Look at your type definitions. "const Type& myObj" is a constant
reference and "const Type myObj" is a constant object. In either case
you are not allowed to change the value after initialization. Any
attempt to change their contents should throw a compiler warning/
error. And yes, you can expect these lines to be very different from
one another. Read some articles on C++ references and constant
modifiers.

Aug 29 '07 #2
On Aug 29, 2:06 pm, spekyuman <spekyu...@gmai l.comwrote:
Look at your type definitions. "const Type& myObj" is a constant
reference and "const Type myObj" is a constant object. In either case
you are not allowed to change the value after initialization. Any
attempt to change their contents should throw a compiler warning/
error.
I'm aware of that. I don't think my question really has anything to
do with const.
And yes, you can expect these lines to be very different from
one another.
Really? Because the output of my tests implies that they are the same
with respect to creation of temporaries and calls to the copy
constructor. I understand that the result of each statement is
different (a reference vs. an object). But, other than that, each
results in a variable that can be used the same way and have the same
lifetime. How did you mean they would be 'very different'?
Aug 29 '07 #3
There are a couple of effects that are coming into play with your code.

1) RVO and NRVO can often remove copies. (You will get much the same
output as gcc with MSVC if you turn on full optimizations as MSVC doesn't
apply NRVO optimisations normally).

2) However, that isn't what's causing the confusion. What is causing the
confusion is that code like:

const testClass t4 = of.getResidentO bject();

isn't actually doing an assignment. It is instead invoking the constructor
for t4 with of.getResidentO bject() as it's argument. That immediately
removes one of your expected copies.

Try using non-const declarations and then declaring it like:

testClass t4;
t4 = of.getResidentO bject();

I would expect to see a difference then.

joe
Aug 29 '07 #4

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

Similar topics

19
2774
by: Christian Engström | last post by:
If you have a function that returns something by value, the gcc compiler (version 3.2.3 on Windows XP with MinGW) converts the returned value from the type you specify in the code, to the const version of that type. Is this a bug that is specific to gcc, or is it a flaw in the language specification that gcc diligently implements? For...
3
1592
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 get no error... 2) Length & Length :: operator+ ( void ) const {return * this;} ... I get the error -> 'return' : cannot convert from 'const...
5
3731
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 their dtor is called immediately and not at the end of the function. to be able to use return objects (to avoid copying) i often assign them to a const...
39
3049
by: JKop | last post by:
Back when I read my first C++ book, I was given the following scenario: class Cheese { public: int number_of_holes; int colour;
2
2341
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 {
8
4086
by: Michael Safyan | last post by:
Dear members of comp.lang.c++, I am a little bit confused about the differences between constant references and values. I understand that it is faster to use a constant reference ("const T&") than a value ("T") since the former does not require copying whereas the latter does, is that correct? Also, I un derstand that "const T&" allows for...
4
6677
by: grizggg | last post by:
I have searched and not found an answer to this question. I ran upon the following statement in a *.cpp file in a member function: static const char * const pacz_HTMLContentTypeHeader = "Content-Type: text/html\r\n"; Why is the second const needed and what does it do? Thanks
13
3961
by: dragoncoder | last post by:
Hi everyone, please consider the following function:- const int& foo ( const double& d ) { return d; } g++ compiles it with warnings and solaris CC gives error. I want to know if the code is correct according to the standard ?
9
2055
by: raylopez99 | last post by:
I'm posting this fragment from another thread to frame the issue clearer. How to pass an object to a function/method call in C# that will guarantee not to change the object?* In C++, as seen below, you can use the 'const' keyword in the function / method declaration. But how to do this in C#? *for example: "void Foo() const;"
0
7693
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
7916
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. ...
0
8117
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...
1
7660
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
6275
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5498
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
3651
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
1207
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
932
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.