Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a copy constructor call guaranteed when passing argument by value

Tags:

c++

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)

like image 699
Toby Brull Avatar asked Jul 24 '14 14:07

Toby Brull


People also ask

Does pass by value call copy constructor?

Passing by value means that the parameter is copied into the function. That calls the copy constructor.

What will happen if a copy constructor receive value as argument?

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.

Does passing by value make a copy?

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.

Why copy constructor is called when we pass an object as an argument?

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.


1 Answers

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.

like image 181
Mike Seymour Avatar answered Nov 01 '22 09:11

Mike Seymour