3

The following two code segments presents the task of initializing variable b as a copy of a. The first code segment initializes the variable using copy initialization (initialization using =). Assume class Apple is simply defined as an empty class: class Apple {};

Apple a;
Apple b = a;

The second code segment initializes the variable using copy initialization as well. Though what is copied in the initialization is the copy of a.

Apple a;
Apple b = Apple(a);

When reading this blindly, it seems as if a copy happens at Apple(a), and another at Apple b = .... In contradiction, overriding the copy constructor of Apple to print something on copy shows that only one copy happens during Apple b = Apple(a).

Are the two statements Apple b = a; and Apple b = Apple(a); identical? Are there instances where they are not identical?

0

1 Answer 1

3

Yes, in concept, for Apple b = Apple(a);, a temporary Apple is constructed from a firstly, then b is copy-initialized from the temporary. Because of copy elision, as the effect b is initialized from a directly.

Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:

  • In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type:

This kind of copy elision is guaranteed since C++17, before C++17 it's an optimization. Compiling with pre-C++17 mode and option prohibiting optimization, you might see the difference between the two cases.

LIVE

4
  • Was this pre-C++17 optimization realized independently between compiler developers? Or, was there formal documentation stating compiler developers should consider implementing this optimization? Dec 8, 2020 at 19:15
  • @TarasPalczynski The standard doesn't require such optimization before C++17, it just allows such optimization. While most compilers I know do support it. Dec 9, 2020 at 1:08
  • Is there some resource that states in a list which compilers support this optimization pre C++17? Or is the only realistic way is to just try on each compiler and see what it does? Dec 9, 2020 at 3:00
  • @TarasPalczynski I'm afraid I don't know that... You might need to check the document of the compilers, or test with the code. Dec 9, 2020 at 3:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.