Home > Software design >  Does declaring a constructor '= default' in a header file break the ODR
Does declaring a constructor '= default' in a header file break the ODR

Time:12-17

If I define the destructor (or any autogenerated constructor) as default like this:

struct A { 
   ~A() = default;
};

And then include this in several translation units, does this break the ODR? Can someone walk me through the steps at on the ODR page? Because i am struggling to understand if the compiler generated destructor will be inline or some other effect to prevent it from breaking the ODR.

CodePudding user response:

No ODR violation. Member functions are implicitly inline if they are defined, defaulted or deleted inside a class definition.

https://en.cppreference.com/w/cpp/language/inline

The implicitly-generated member functions and any member function declared as defaulted on its first declaration are inline just like any other function defined inside a class definition.

// header file

// OK, implicit inline
struct A  {
    ~A() {}
};
// header file

// OK, implicit inline
struct A  {
    ~A() = default;
};
// header file

struct A  {
    ~A();
};


// NOT ok, ODR violation when header is included in more than 1 TU
A::~A() {};
// header file

struct A  {
    ~A();
};


// NOT ok, ODR violation when header is included in more than 1 TU
A::~A() = default;
  • Related