代码之家  ›  专栏  ›  技术社区  ›  Fantastic Mr Fox

在头文件中声明构造函数“=default”会破坏ODR吗

  •  1
  • Fantastic Mr Fox  · 技术社区  · 4 年前

    如果我将析构函数(或任何自动生成的构造函数)定义为默认值,如下所示:

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

    ODR 页因为我很难理解编译器生成的析构函数是否是内联的,或者是其他一些效果,以防止它破坏ODR。

    1 回复  |  直到 4 年前
        1
  •  2
  •   bolov    4 年前

    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;
    
    推荐文章