Is a call to the copy constructor guaranteed to pass an argument by value

Someone suggested that the optimizer should be allowed to freely exchange parameter-transfer-constant-reference and parameter-transfer-by-value in any function that does not change the parameter. Is this allowed by the C ++ standard?

Or indicated otherwise 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 mean that "xxx" is always printed? (Link to standard grade)

+6
source share
1 answer

Yes, the copy constructor will be used here. Copying permissions is allowed only under certain circumstances specified in C ++ 11 12.8 / 31:

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

None of them apply here, although the third will apply if you pass a temporary value:

 foo(MyClass()); 

In this case, the message may not be printed.

In addition, if the copy constructor had no side effects, then in any case, the copy can be canceled in accordance with the “as is” rule (regardless of whether the argument was temporary), since this will not affect the program’s visible behavior.

+8
source

Source: https://habr.com/ru/post/972770/


All Articles