15

Is the following legal according to the C++11 standard (= default outside the definition of the class) ?

// In header file
class Test
{
    public:
        Test();
        ~Test();
};

// In cpp file
Test::Test() = default;
Test::~Test() = default;
ildjarn
  • 62,044
  • 9
  • 127
  • 211
Vincent
  • 57,703
  • 61
  • 205
  • 388
  • 9
    This is fine, the standard even uses it in an example (`§8.4.2/3`). `= default` and `= delete` are just "normal" function bodies (as per spec, anyways), i.e. what you'd write in a *definition*. – Xeo Jan 10 '13 at 11:57
  • 2
    Note that a defaulted definition can appear after the first declaration of the function while a deleted definition has to be the first declaration of the function. – MWid Jan 10 '13 at 12:01
  • @Xeo Sounds like an answer. – Christian Rau Jan 10 '13 at 12:05
  • Note that a constructor that is defaulted in this way, is still a user-provided constructor. As a result, your class `Test` is not a trivial class. See http://stackoverflow.com/a/7169675/396551 – Sjoerd Jan 10 '13 at 12:06

1 Answers1

12

Yes, a special member function can be default-defined out-of-line in a .cpp file. Realize that by doing so, some of the properties of an inline-defaulted function will not apply to your class. For example, if your copy constructor is default-defined out-of-line, your class will not be considered trivially copyable (which also disqualifies it from being recognized as a POD). Similarly, a default-defined out-of-line destructor will disqualify your type from being trivial (or POD).

This can be useful if you wish to have a non-inline copy-constructor and control over where it is defined (perhaps to take control over generated template definitions it will require), but don't wish to manually define it yourself with a hand-crafted member-initializer list, which would be laborious and could go stale under maintenance.

Adam H. Peterson
  • 4,511
  • 20
  • 28