假设我有一个类型,并且希望将其默认构造函数设置为私有。我可以编写以下内容:
class C {
C() = default;
};
int main() {
C c; // error: C::C() is private within this context (g++)
// error: calling a private constructor of class 'C' (clang++)
// error C2248: 'C::C' cannot access private member declared in class 'C' (MSVC)
auto c2 = C(); // error: as above
}
好的。
但随后,构造函数原来并不像我想象的那样私有:
class C {
C() = default;
};
int main() {
C c{}; // OK on all compilers
auto c2 = C{}; // OK on all compilers
}
这让我感到非常惊讶、意外,而且明确是不希望的行为。为什么这是可以的呢?
C c{};
不是聚合初始化吗,因此不会调用构造函数? - NathanOliverC
是一个聚合体。 - Kerrek SB=default
构造函数,那似乎更合理。 但私有的=default
构造函数似乎是一个不应该被忽视的重要事情。 而且,class C { C(); } inline C::C()=default;
这个也相当不同,有点令人惊讶。 - Yakk - Adam Nevraumontprivate
覆盖编译器生成的默认值为public
。 - NathanOliver