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.