Reputation: 4386
I have the following code:
#include <iostream>
using namespace std;
class A
{
public:
A ()
{
cout<<"cons"<<endl;
}
~A ()
{
cout<<"dest"<<endl;
}
};
A
gokul (void)
{
A p;
return p;
}
int
main ()
{
A a = gokul();
cout<<"done\n";
}
When I run it. I get the following output:
cons
done
dest
I was expecting the output to be:
cons --> p created,
cons --> for a, gokul returning
dest --> p destroyed, gokul returned
done
dest --> a destroyed, main returned
as the local variable "p" will be destroyed when the function gokul returns and the new variable "a" will be created, no? I have compiled with all three standards 03, 11 & 14 and I get the same result. ~
Upvotes: 0
Views: 228
Reputation: 1874
If you have optimization turned on then you get this output because of compiler optimization Copy Elision
enter link description here
Or if you run your program in debug mode (without optimization), you don't simply trace copy constructor that is used as @PaulMcKenzie explained.
You can try compile without optimization: /Od
(in visual studio), -O0
in gcc. Or just run in debug mode. And then back to optimization version by /O2
or -O2
.
Beware that from C++11 compiler can use move constructor if you swith to non optimized version /0d
and still you don't get output. So you need to trace move constructor
A(const A&& o){
cout << "move ctor" << endl;
}
Upvotes: 0
Reputation: 35454
Your code failed to trace the copy constructor. You need to do this to get a better picture of when an object is created.
#include <iostream>
using namespace std;
class A
{
public:
A() { cout<<"cons"<<endl; }
~A() { cout<<"dest"<<endl; }
A(const &A) { cout << "copy constructed" << endl;}
};
A gokul (void)
{
A p;
return p;
}
int main ()
{
A a = gokul();
cout<<"done\n";
}
When you run this code in Visual Studio 2015, no optimizations, the output is as follows:
cons
copy constructed
dest
done
dest
When you change to release mode, the output is now this:
cons
done
dest
The reason for the second output to not have copy construction is due to the Named Return Value Optimization
that is done to remove the copy.
However the point is that you really can't predict how many times a copy constructor is called. As you can see, the unoptimized version also works correctly.
Upvotes: 5