3

Quoted from In C++, a Copy Constructor may be called in following cases:

  1. When an object of the class is returned by value.
  2. When an object of the class is passed (to a function) by value as an argument.
  3. When an object is constructed based on another object of the same class.
  4. When compiler generates a temporary object.

I think the context is about the legacy C++ rather than the modern one.

My comments

  • Option 1. The copy ctor may not be called due to copy elision on "returning an object as well as a temporary object by value" provided by modern c++.
Foo Method1(){return Foo{};}
Foo Method2(){Foo obj{}; return obj;}
  • Option 2. The copy ctor will not be called due to copy elision on "passing a temporary object by value" provided by modern c++.
void Method3(Foo param){}
Method3(Foo{});
  • Option 3. The copy ctor will not be called due to copy elision on "initializing object by a temporary object" provided by modern c++.
Foo obj {Foo{}};
  • Option 4. I don't understand this option. I cannot find any example how compiler calls copy constructor when generating a temporary object. I did compile with legacy C++ (with -fno-elide-constructors) and modern C++, they both do NOT call the copy constructor. Or is the option 4 wrong?
Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165
  • Historically, have the legacy c++ called copy constructor when generating a temporary object? Honestly, it does not make sense. What is the purpose of calling copy constructor when generating a temporary object? – Second Person Shooter Mar 11 '21 at 06:04
  • https://stackoverflow.com/a/9945598/11971304, here's something for reference. Modern c++ compilers still would prefer elision for temporary objects copy. if you are looking for an answer which says "what version of c++ compiler is required to invoke a copy constructor for temporary object creation" then that changes the context of question!. – mahee96 Mar 11 '21 at 06:10
  • How "legacy" do you want to get? We can go all the way to 1982's "CFront" if you want... :) – Jeremy Friesner Mar 11 '21 at 06:34
  • @JeremyFriesner: From the first C++ created by Bjarne Stroustrup. :-) – Second Person Shooter Mar 11 '21 at 06:40
  • "Or is the option 4 wrong?" No, the full absence of a compiler with this behavior is no evidence, that this option is not standard compliant. Good question however! I guess there's no robust way to force that for all standard-conform modern compilers even before C++17's guaranteed copy elision, but cannot prove it. – Secundi Mar 11 '21 at 10:11

0 Answers0