允许构造函数调用私有方法的默认参数

Default argument allowing constructor to call private method

我有 class

class A
{
public:
    class Key
    {
        Key() {}
        Key(Key const &) {}
    };

    A(Key key, int a = 5) {}
};

Key 的构造函数是私有的,因此任何人都不能构造对象 A。但是,使用以下代码:

int main() {
    A a(A::Key()); // this compiles !!!
    A a2(A::Key(), 5); // this doesn't
    // somehow defaulting the argument causes the private constructor
    // to be OK - no idea why
    return 0;
}

通过在我的构造函数中使用 int a 的默认参数,编译器愉快地编译了我对 A::Key() 的用法,尽管它是私有的。但是,如果我明确地为 a 提供一个值,编译器会正确地识别出我正在尝试使用私有构造函数并出错。为什么是这样?是否有某种方法可以强制编译器也对第一个示例出错?

请参阅 here 以获取实际示例。

这是因为最烦人的解析。

A a(A::Key());

不创建名为 aA 并使用临时 A::Key 构造它。它创建了一个函数 a returns 一个 A 并采用一个未命名的指针指向 returns 一个 A::Key.

的函数

如果向其添加一对括号,将会出现编译错误

A a((A::Key()));

您正在尝试调用私有构造函数。或者,您可以使用统一初始化,这也会消除歧义并导致编译错误

A a(A::Key{});