I wasn't able to find a concrete answer for the following question:
Consider the following code:
Obj f() {
Obj o2;
return o2;
}
int main() {
Obj o1 = f();
return 0;
}
How many times is the copy constructor activated without compiler optimization?
In case there isn't move constructor, isn't it one time for copying o2 to the caller function and another time for constructing o1?
In case there is move constructor, isn't it one time for copying o2 to the caller function and another time for constructing o1 (2nd time is move const)?
Before C++17, yes there are two copy constructor calls (both of which can be elided even if they have side-effects). You can see this with -fno-elide-constructors
in gcc/clang.
Since C++17 due to the new temporary materialization rules there is just one copy involved inside f
(which, again, can be elided).
To be accurate all of them are moves, not copies.