Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should a default destructor C++11 style go, header or cpp?

Tags:

c++11

In C++11 a default implementation of constructor(s), destructor and copy/move operators can be specified with "= default". Where to put the "= default", in header file, where the class definition is, or in the source file (cpp)?

In header file Test.h:

class Test
{
public:
    ~Test() = default;
};

In source file Test.cpp:

class Test
{
public:
    ~Test();
};

#include "Test.h"
Test::~Test() = default;
like image 330
Tomasz Jakubowski Avatar asked Jul 07 '16 09:07

Tomasz Jakubowski


1 Answers

I have to disagree with rubenvb. You aren't forced to put the explicit default destructor in the header file. In fact, there is a use case for which it's perfectly valid (and necessary) to put the explicit default destructor in the .cpp file.

Consider the case where you forward declare a class in the header file, and use it with one of the smart pointers templates. As the implicit destructor doesn't have the complete declaration of the forward declared class, it cannot properly do its deletion. Therefore, you need to move the destructor definition to the C++ file, where you should have access to the complete declaration.

In A.hpp:

#pragma once
#include <memory>
class B;

class A 
{
private:
  std::unique_ptr<B> my_b;
public:
// ~A() = default; 
// defining the default destructor would fail as 
// class B is still a partial class here
  ~A();
};

In A.cpp:

#include "A.hpp"

// the previously forward declared class B is now included here
#include "B.hpp"

// we can use the default destructor here as B is
// no longer a partial class
A::~A() = default; 
like image 59
Gajo Petrovic Avatar answered Sep 21 '22 08:09

Gajo Petrovic