在头文件中声明构造函数“= default”是否会破坏 ODR
Does declaring a constructor '= default' in a header file break the ODR
如果我像这样将析构函数(或任何自动生成的构造函数)定义为默认值:
struct A {
~A() = default;
};
然后将其包含在多个翻译单元中,这会破坏 ODR 吗?有人可以指导我完成 ODR 页面上的步骤吗?因为我很难理解编译器生成的析构函数是内联的还是其他一些效果来防止它破坏 ODR。
没有 ODR 违规。如果在 class 定义中定义、默认或删除成员函数,则它们是隐式内联的。
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;
如果我像这样将析构函数(或任何自动生成的构造函数)定义为默认值:
struct A {
~A() = default;
};
然后将其包含在多个翻译单元中,这会破坏 ODR 吗?有人可以指导我完成 ODR 页面上的步骤吗?因为我很难理解编译器生成的析构函数是内联的还是其他一些效果来防止它破坏 ODR。
没有 ODR 违规。如果在 class 定义中定义、默认或删除成员函数,则它们是隐式内联的。
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;