In this very simple program the constructor is called once, but the destructor is called twice:
#include <iostream>
using namespace std;
class CTest
{
public:
int m_val;
CTest(int val);
~CTest();
};
CTest::CTest(int val) : m_val(val)
{
cout << "construct " << m_val << '\n';
}
CTest::~CTest()
{
cout << "delete " << m_val << '\n'; m_val = 77777;
};
int main() {
CTest a(2);
CTest b = a;
}
Output:
construct 2
delete 2
delete 2
Expected output:
construct 2
delete 2
This is actually because of the implicit copy constructor (correct me if I'm wrong).
Do I need to define a copy constructor here or is it safe to rely on the implicit copy constructor?
Same question if I have non POD class members (such as std::string
)?