copy constructors
I've got an example code with copy constructors and would like to know if it can possibly output in some other way (on other compiler/platform):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#include <iostream>
using namespace std;
struct X
{
X()
{
cout << "called default construct" << endl;
}
X(const X& ref)
{
cout << "called copy construct" << endl;
}
void fx() {}
};
// no copy constructor called here
X newconstruct()
{
X xnew;
return xnew;
}
// two copy const.
const X fy(const X x)
{
//x.fx(); // const disallows!
return x;
}
// two copy const.
X fz(X x)
{
x.fx();
return x;
}
int
main(int, char**)
{
// just one def. construct -- always so? Why?
newconstruct();
cout << endl;
// one def. construct
X x;
cout << endl;
cout << endl;
cout << "fy: " << endl;
fy(x); // two copies -- always so? Why?
cout << "fz: " << endl;
fz(x); // two copies -- always so? Why?
return 0;
}
|
The copy constructor will be called every time a copy is made.
So a copy is made first when the function is called because the object is copied into the parameter variable.
Then when the parameter variable is returned at the end of the function another copy is made.
I believe that some compilers or compiler options may optimise away the returned copy.
Topic archived. No new replies allowed.