Recently I was testing some C++ deep and dark corners and I got confused about one subtle point. My test is so simple actually:
// problem 1
// no any constructor call, g++ acts as a function declaration to the (howmany())
// g++ turns (howmany()) into (howmany(*)())
howmany t(howmany());
// problem 2
// only one constructor call
howmany t = howmany();
My expectation from above line was; first howmany()
constructor call will produce one temporary object and then compiler will use that temporary object with copy-constructor in order to instantiate t. However, output of compiler really confused me because output shows only one constructor call. My friends mentioned me about compiler pass-by-value optimization but we are not sure about it. I want to learn what does happen here ?
Output of problem 2 is below. problem 1 is completely beyond object instantiation because compiler behaves it as a function pointer declaration.
howmany()
~howmany()
My test class is:
class howmany {
public:
howmany() {
out << "howmany()" << endl;
}
howmany(int i) {
out << "howmany(i)" << endl;
}
howmany(const howmany& refhm) {
out << "howmany(howmany&)" << endl;
}
howmany& operator=(const howmany& refhm) {
out << "operator=" << endl;
}
~howmany() {
out << "~howmany()" << endl;
}
void print1() {
cout << "print1()" << endl;
}
void print2() {
cout << "print2()" << endl;
}
};
Yes, this is one of the optimization compiler may do. The compiler is allowed to eliminate temporary object creation even if copy constructor has side effects!
This is the most vexing parse here:
In order to fix this you need to add an extra set of parens:
clang
is very helpful here and warns you:The other way to fix this is to use C++11 uniform initialization syntax:
Update
To address part
2
which you added to the question the draft standard allows for omission of the copy/move construction in some cases. We can see this from section12.8
Copying and moving class objects paragraph 31 which says:and includes the following bullet:
After getting clues from above answers I found real problem. In my case, especially problem 2, compiler eliminates the copy construction process because return value of howmany() constructor call is completely same to the howmany t object, for that reason compiler just eliminates copy-construction process in order to make optimization. More detail of this problem is covered in wikipedia, please look to there.Return value optimization
-fno-elide-constructors is one of g++ flags which is responsible from disabling the optimizations. In cmake we just need to set it.
set(CMAKE_CXX_FLAGS "-fno-elide-constructors")
After disabling optimizations, the output of program turned what i was expecting.
Thanks :)