473,386 Members | 1,842 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,386 software developers and data experts.

Please explain this unexpected behavior (regarding return-by-value)


Hi, I came across this unexpected behavior while working on something
else. I am attempting to return a custom type by value from a global
function. I have a trace in the custom class's copy constructor, and I
expected this code to tell me that the custom copy constructor had been
called twice. Instead, it's only called once and the program executes
correctly.

Is this an optimization related to my compiler (g++ v4.0.1) or is this
specified by the standard? Can somebody clear this behavior up for me?

Thanks in advance!

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// start example source
#include <string>
#include <iostream>
using std::string;
using std::cout;
using std::endl;

class Test
{
string member_;

public:
Test(const string& s) : member_(s) { }
Test(const Test& copy) : member_(copy.member_) {
cout << "copy" << endl;
}

void out() { cout << member_ << endl; }

};

Test test_by_value(const Test& in)
{

Test temp(in); // expect a copy here while constructing temp
return temp; // also expect a copy here to return the value of
temp, which currently exists on the stack
}

int main()
{
Test t("hello");
Test v = test_by_value(t);
v.out();

return 0;
}
/*
expected output:
copy
copy
hello
actual output:
copy
hello

how is the copied value being returned from test_by_value() without a
second copy (since temp is a stack var)?
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

Nov 10 '06 #1
4 1584
* du********@gmail.com:
Hi, I came across this unexpected behavior while working on something
else. I am attempting to return a custom type by value from a global
function. I have a trace in the custom class's copy constructor, and I
expected this code to tell me that the custom copy constructor had been
called twice. Instead, it's only called once and the program executes
correctly.
Copy constructor calls are allowed to be optimized away -- in many
situations -- regardless of possible side-effects in the copy constructor.

So generally you can't "expect" any specific number of calls.

For your specific example, look up RVO and NRVO.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 10 '06 #2

du********@gmail.com wrote:
Hi, I came across this unexpected behavior while working on something
else. I am attempting to return a custom type by value from a global
function. I have a trace in the custom class's copy constructor, and I
expected this code to tell me that the custom copy constructor had been
called twice. Instead, it's only called once and the program executes
correctly.

Is this an optimization related to my compiler (g++ v4.0.1) or is this
specified by the standard? Can somebody clear this behavior up for me?

Thanks in advance!

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// start example source
#include <string>
#include <iostream>
using std::string;
using std::cout;
using std::endl;

class Test
{
string member_;

public:
Test(const string& s) : member_(s) { }
Test(const Test& copy) : member_(copy.member_) {
cout << "copy" << endl;
}

void out() { cout << member_ << endl; }

};

Test test_by_value(const Test& in)
{

Test temp(in); // expect a copy here while constructing temp
return temp; // also expect a copy here to return the value of
temp, which currently exists on the stack
}

int main()
{
Test t("hello");
Test v = test_by_value(t);
v.out();

return 0;
}
/*
expected output:
copy
copy
hello
actual output:
copy
hello

how is the copied value being returned from test_by_value() without a
second copy (since temp is a stack var)?
*/

Because the following:

Test v = test_by_value(t);

is usually optimized to:

Test v(test_by_value(t));

which is completely legal, btw.

Note the same happens with a primitive:
int x(99);
int n = x; // is actually a copy

Nov 10 '06 #3

<du********@gmail.comwrote in message
news:11**********************@m73g2000cwd.googlegr oups.com...
Is this an optimization related to my compiler (g++ v4.0.1) or is this
specified by the standard? Can somebody clear this behavior up for me?
VS2005 does a similar optimization, the NRVO
(http://msdn.microsoft.com/library/de...rvo_cpp05.asp).

--
Marco
Nov 10 '06 #4
On 9 Nov 2006 20:58:52 -0800, du********@gmail.com wrote:
>Is this an optimization related to my compiler (g++ v4.0.1) or is this
specified by the standard? Can somebody clear this behavior up for me?
This 'optimization' (the (N)RVO hack) is compiler specific. IIRC, you
can turn it off with a compiler switch for g++.

Best wishes,
Roland Pibinger
Nov 10 '06 #5

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

Similar topics

17
by: matthias_k | last post by:
Hi, I am currently implementing a solver for linear optimization problems using the revised simplex method and I stumbled accross some strange behavior regarding the treatment of the number 0....
25
by: REH | last post by:
Someone more articulate than me please explain to Ioannis Vranos why the following two programs both exhibit undefined behavior: > #include <iostream> > #include <cstring> > > class SomeClass...
4
by: Generic Usenet Account | last post by:
I am seeing some unexpected behavior while using the STL "includes" algorithm. I am not sure if this is a bug with the template header files in our STL distribution, or if this is how it should...
12
by: Sanjeev | last post by:
Output of followin program at Turbo C++ 3.0 is 7 ( Not 2 or 3). Please explain why ? //////////////////////////////////////////////// #include<stdio.h> #include<string.h> void main() {
9
by: Jeff Louie | last post by:
In C# (and C++/cli) the destructor will be called even if an exception is thrown in the constructor. IMHO, this is unexpected behavior that can lead to an invalid system state. So beware! ...
1
by: Terrance | last post by:
Hello, I was wondering if someone can help me understand something. Below is some code that I got from the MS website that is suppose to authenticate for the username and password on the local...
1
by: matko | last post by:
When the height of some text is to be calculated, I get different height values depending on where transformation is done. This only occurs for some fonts. F.ex., when height is calculated for...
1
by: Kevin Walzer | last post by:
I'm trying to toggle the visibility of a Tkinter widget using pack_forget(), and I'm running into unexpected behavior. The widget "hides" correctly, but does not become visible again. My sample...
7
TheSmileyCoder
by: TheSmileyCoder | last post by:
I have this code: Public Function SpecialFolderPath(strFolder As String) As String Dim objWSHShell As Object Dim strSpecialFolderPath 'On Error GoTo ErrorHandler ' Create a...
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:
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...
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...
0
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...
0
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,...
0
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...

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.