使用`= default`允许访问私有构造函数

时间:2020-11-09 19:20:01

标签: c++ c++11

我有代码:

class Key
{
private:
    // If I use the = default keyword here, the line "Key a = {};" compiles
    // If I instead use Key() {}, that same line does not compile (as the constructor is private)
    Key() = default;

    Key(Key const &) = default;
    Key(Key &&) = default;

    Key & operator=(Key const &) = default;
    Key & operator=(Key &&) = default;
};

int main()
{
    // This line compiles when = default is used, but not when an empty constructor is used
    Key a = {};
    return 0;
}

在此特定实例中,默认构造函数和空构造函数之间有什么区别?另外,我希望对此不进行编译,这是在此处显式编写自己的空构造函数吗?注意:这已在GCC 8.3和Clang 10.0上进行了测试,结果相同。

1 个答案:

答案 0 :(得分:7)

在C ++ 20之前的默认构造函数为default的情况下,此代码将编译,因为具有默认构造函数的类为aggregate,并且您可以通过聚合初始化来初始化聚合

Key a = {}; // interpreted as aggregate initialization and bypasses access qualifier on constructor

此代码无法在C ++ 20或更高版本中编译,因为默认构造函数使其无法聚合:

Key a = {}; // interpreted as calling a constructor, since Key is no longer an aggregate.

在这种情况下,由于构造函数是私有的,因此编译器会尝试实际调用构造函数,而不能进行调用。

有空的时候

Key() { };

您的类不再具有任何C ++方言的集合,因为它具有用户定义的非默认构造函数。