Quoted from In C++, a Copy Constructor may be called in following cases:
- When an object of the class is returned by value.
- When an object of the class is passed (to a function) by value as an argument.
- When an object is constructed based on another object of the same class.
- 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?