levzettelin
levzettelin

Reputation: 2972

Is a copy constructor call guaranteed when passing argument by value

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

Answers (1)

Mike Seymour
Mike Seymour

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:

  • in a return statement ...
  • in a throw-expression ...
  • when a temporary class object ... would be copied/moved ...
  • when the exception-declaration of an exception handler declares an object of the same type ... as the exception object

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

Related Questions