【问题标题】:Does declaring a constructor '= default' in a header file break the ODR在头文件中声明构造函数 '= default' 是否会破坏 ODR
【发布时间】:2021-12-17 03:04:26
【问题描述】:

如果我像这样将析构函数(或任何自动生成的构造函数)定义为默认值:

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

然后将其包含在几个翻译单元中,这会破坏 ODR 吗?有人可以引导我完成ODR 页面上的步骤吗?因为我很难理解编译器生成的析构函数是否会内联或其他一些效果以防止它破坏 ODR。

【问题讨论】:

  • 类定义中默认的所有成员函数都是隐式内联的。

标签: c++ one-definition-rule


【解决方案1】:

没有违反 ODR。如果成员函数在类定义中被定义、默认或删除,则它们是隐式内联的。

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

隐式生成的成员函数和任何成员函数 在其第一个声明中声明为默认值是内联的,就像 在类定义中定义的任何其他函数。

// 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;

【讨论】:

  • 呃,那不是我期望找到答案的地方。似乎应该有一个来自构造函数页面的链接。
  • @FantasticMrFox 也许吧。该标准是相互关联的。我从经验中知道这一点。
猜你喜欢
  • 1970-01-01
  • 2020-09-13
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 2017-03-17
  • 1970-01-01
相关资源
最近更新 更多