I have the following C++ code (VS2013):
#include <iostream>
using namespace std;
class A {
int i;
public:
A(int i) : i(i) {
cout << "DEFAULT CTOR " << i << endl;
}
A(const A &o) : i(o.i) {
cout << "COPY CTOR " << i << endl;
}
~A() {
cout << "DTOR " << i << endl;
}
friend A f(const A &, A, A *);
};
A f(const A &a, A b, A *c) {
return *c;
}
int main() {
f(1, A(2), &A(3));
}
It produces the following output:
DEFAULT CTOR 1
DEFAULT CTOR 3
DEFAULT CTOR 2
COPY CTOR 3
DTOR 2
DTOR 3
DTOR 3
DTOR 1
The first 3 are parametric constructors (wrongfuly outputing "DEFAULT CTOR" but that doesn't matter), which are called prior to calling f.
Then, when the return *c; line is run, the copy constructor with value 3 is run, followed by the destruction of the object with value 2.
Finally, at the end of main's scope, the remaining objects (3, 3, 1) are destructed.
I don't understand this behavior, and found no explanation to it.
Can anyone elaborate as to the order of things happening?
Specifically:
Why is the third object
&A(3)constructed before the second objectA(2)? Does this have anything to do with their creation (the third is by reference, the second is by value), or with the wayfis defined (the second is by value, the third is a pointer)?When
return *c;runs, a copy of the third object is created to be returned. Then, the only object being destructed before returning is the second object. Again, does this have anything to do with their creation, or with the wayfis defined?
Thanks in advance.