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)
Passing by value means that the parameter is copied into the function. That calls the copy constructor.
If the argument is passed by value, its copy constructor would call itself to copy the actual parameter to formal parameter. This process would go on until the system runs out of memory. So, we should pass it by reference , so that copy constructor does not get invoked.
By definition, pass by value means you are making a copy in memory of the actual parameter's value that is passed in, a copy of the contents of the actual parameter.
Because passing by value to a function means the function has its own copy of the object. To this end, the copy constructor is called.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With