gpt4 book ai didi

c++ - 什么时候私有(private)构造函数不是私有(private)构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:47:08 27 4
gpt4 key购买 nike

假设我有一个类型,我想将其默认构造函数设为私有(private)。我写了以下内容:

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
}

很好。

但是,构造函数并不像我想象的那样私有(private):

class C {
C() = default;
};

int main() {
C c{}; // OK on all compilers
auto c2 = C{}; // OK on all compilers
}

这让我感到非常惊讶、出乎意料且明显不受欢迎的行为。为什么这样可以?

最佳答案

技巧在 C++14 8.4.2/5 [dcl.fct.def.default] 中:

... A function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration. ...

这意味着 C 的默认构造函数实际上不是 用户提供的,因为它在第一次声明时已明确默认。因此,C 没有用户提供的构造函数,因此是每个 8.5.1/1 [dcl.init.aggr] 的聚合:

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

关于c++ - 什么时候私有(private)构造函数不是私有(private)构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44570180/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com