Reputation: 2972
Someone suggested to me that an optimizer is allowed to freely interchange parameter-passing-by-const-reference and with parameter-passing-by-value in any function that does not modify the parameter. Is that allowed by the C++ standard?
Or stated differently, in the code
struct MyClass {
MyClass(MyClass const& mc) { std::cout << "xxx" << std::endl; }
};
void foo(MyClass mc) { }
MyClass mc;
foo(mc);
does the C++ standard guarantee that "xxx" is always printed? (Reference to standard appreciated)
Upvotes: 6
Views: 132
Reputation: 254631
Yes, the copy constructor will be used here. Copy elision is only allowed in certain circumstances, specified by C++11 12.8/31:
return
statement ...None of these apply here, although the third would apply if you passed a temporary value:
foo(MyClass());
In this case the message might not be printed.
Furthermore, if the copy-constructor had no side effects, then the copy could be elided under the "as-if" rule in any case (whether or not the argument were a temporary) since doing so would not effect the program's visible behaviour.
Upvotes: 8