Here is the code which confuses me:
#include <iostream>
using namespace std;
class B {
public:
B() {
cout << "constructor\n";
}
B(const B& rhs) {
cout << "copy ctor\n";
}
B & operator=(const B & rhs) {
cout << "assignment\n";
}
~B() {
cout << "destructed\n";
}
B(int i) : data(i) {
cout << "constructed by parameter " << data << endl;
}
private:
int data;
};
B play(B b)
{
return b;
}
int main(int argc, char *argv[])
{
#if 1
B t1;
t1 = play(5);
#endif
#if 0
B t1 = play(5);
#endif
return 0;
}
Environment is g++ 4.6.0 on Fedora 15.
The first code fragment output is as follows:
constructor
constructed by parameter 5
copy ctor
assignment
destructed
destructed
destructed
And the second fragment code output is:
constructed by parameter 5
copy ctor
destructed
destructed
Why are are three destructors are called in the first example, while in the second it is only two?
First Case:
t1by calling default constructor ofB.play(), A temporary object ofBis created by usingB(int i).5is passed as an and object ofBis created, andplay()is called.return b;insideplay()causes thecopy constructorto be called for returning a copy of object.t1 =calls the Assignemnt operator to assign the returned object copy tot1.#3.#2.t1.Second case:
Bis created by calling parameterized constructor ofBwhich takesintas a paraemter.B.#1.t1.One destructor call is less in Second Case because, in second Case the compiler uses Return value Optimization and elides the call to create an additional temporary object while returning from
play(). Instead theBaseobject is created in the location where the temporary would have been assigned.