473,800 Members | 2,406 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 1816
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
2808
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 example, the below program produces the output Constant Mutable
3
1600
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 class Length' to
5
3757
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 reference. now, casting a const return object from a function to a non-const reference to this...
39
3101
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
2368
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
4099
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 polymorphism whereas "T" will generate code cuttting. On the former points, I am fairly confident......
4
6697
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
3985
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
2064
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
9551
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10275
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10253
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 most users, this new feature is actually very convenient. If you want to control the update process,...
1
7576
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5471
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
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
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2945
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.