1

is any point(e.g faster compilation) of separate definition and declaration of default constructor/destructor? I met with such design and I don't understand why someone do not keep it just in .hpp file.

// A.hpp
class A
{
public:
    A();
    ~A();
};
// A.cpp
#include "A.hpp"
A::A() = default;
A::~A() = default;
thebarylowi
  • 55
  • 1
  • 1
  • 7

2 Answers2

5

Consider PIMPL idiom implemented with smart pointers:

// X.h:
class X {
  class Impl;
  std::unique_ptr<Impl> pimpl_;
public:
  ~X() = default;
  ...
};

Inclusion of such a header file into source will cause a compilation error, since X::Impl is an incomplete type there and therefore cannot be deleted.

A solution is to move destructor definition into a source:

// X.h:
class X {
  class Impl;
  std::unique_ptr<Impl> pimpl_;
public:
  ~X();
  ...
};

Plus:

// X.cpp:
class X::Impl { ... };

X::~X() = default;  // X::Impl is complete here
Daniel Langr
  • 22,196
  • 3
  • 50
  • 93
2

This is done to avoid inlining the constructor and destructor. One reason is when there are members of smart-pointers to incomplete types when their definitions are only available in the .cpp file.

There is a difference between defaulting the constructor/destructor in the declaration vs the definition. The former can be noexcept automatically whereas the latter has to be declared with noexcept. Also, the constructor not declared as default makes the type non-trivial.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271