1

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)?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 3
    You have two `CTest` instances in main, why do you only expect one of them to be destructed? – simon Dec 14 '18 at 15:09
  • 1
    Yes, and yes. Generally speaking you only need a copy constructor if your destructor releases resources (freeing memory for instance). – john Dec 14 '18 at 15:09
  • 1
    @john And if it allocates its dynamic memory through `std::unique_ptr`, `std::vector` and the like, not even for that. – Davislor Dec 14 '18 at 15:23
  • 2
    @Davislor Yes, I should have said directly releases resources, if it delegates that to some other class then (assuming a well written class) the other class will also handle copying. – john Dec 14 '18 at 15:38
  • 1
    @john And your main point is entirely correct! There are many other kind of resources, and writing another class that releases them manually just so your outer class can contain it only makes your framework more complicated. RAII with STL containers is a great technique, though. – Davislor Dec 14 '18 at 15:42

0 Answers0