#include <iostream>
using namespace std;
int gc = 0;
struct A {
int id;
A():id(gc++) { cout << "Constructed #" << id << "\n"; }
A(const A& b):id(gc++) { cout << "Copying from " << b.id << " to " << id << "\n"; }
~A() { cout << "Destructed #" << id << "\n"; }
};
A f() {
A a;
cout << "Exiting f()" << "\n";
return a;
}
int main() {
A b = f();
cout << "Exiting main()" << "\n";
return 0;
}
The output produced (with no optimization (-O0
), and using either of these compilers: g++ 4.6.3, g++ 4.8.1, clang++ 3.0 on Ubuntu):
Constructed #0
Exiting f()
Exiting main()
Destructed #0
My guess for copy constructor not being called (despite it having observable side effects), and object a
not getting destroyed in f()
) is NRVO (similar case as described in: https://stackoverflow.com/a/3906038/1857518).
My questions:
- Is the output of this program well specified by C++ standards ?
- If (1) is true, then which one of the following case it is:
- The output will always exactly be this
- There exist a legal & finite set of outputs, say,
Out
(such that|Out| > 1
). And a conformant compiler can produce any one from the setOut
. If this is the case, what does the setOut
looks like.