1

I got confused about copy constructor in c++.
Code is below:

#include <iostream>
using namespace std;

class HasPtrMem {
public:
    HasPtrMem() : d(new int(0)) {
        cout << "Construct : " << ++n_cstr << endl;
    }
    HasPtrMem(const HasPtrMem & h) : d(new int(*h.d)) {
        cout << "Copy construct : " << ++n_cptr << endl;
    }
    ~HasPtrMem() {
        cout << "Destruct : " << ++n_dstr << endl;
        delete d;
    }

    int* d;
    static int n_cstr;
    static int n_dstr;
    static int n_cptr;
};

int HasPtrMem::n_cstr = 0;
int HasPtrMem::n_dstr = 0;
int HasPtrMem::n_cptr = 0;

HasPtrMem GetTemp() {
    return HasPtrMem();
}

int main() {
    HasPtrMem a = GetTemp();
    return 0;
}

Compile it with g++ xxx.cc, and then run it with ./a.exe
Output is

Construct : 1
Destruct : 1

Copy constructor is not called.
Env:

windows10
g++: (MinGW-W64 i686-ucrt-posix-dwarf, built by Brecht Sanders) 12.2.0

Any help is appreciated.
Thanks you.

shanfeng
  • 503
  • 2
  • 14
  • Search for "copy elision" (or "return value optimization"). – wohlstad May 29 '23 at 11:21
  • `HasPtrMem a = GetTemp();`: from [Copy initialization](https://en.cppreference.com/w/cpp/language/copy_initialization) _"...First, if T is a class type and the initializer is a prvalue expression whose cv-unqualified type is the same class as T, the initializer expression itself, rather than a temporary materialized from it, is used to initialize the destination object: see [copy elision](https://en.cppreference.com/w/cpp/language/copy_elision)...."_ – Richard Critten May 29 '23 at 11:22
  • The compiler is allowed to optimize copies away in several instances. From C++17, the compiler is even required to do so in certain cases, one of them being initialization such as `T x = f();` when `f()` returns a class type `T` (which is initialization from a prvalue). You can not rely on the copy constructor being called in these cases -- optimizing compilers usually try to avoid copies as much as possible / allowed by the C++ standard. – chi May 29 '23 at 11:28

0 Answers0