D
duffdevice
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)?
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
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)?
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////