gpt4 book ai didi

c++ - 静态方法类实例化

转载 作者:行者123 更新时间:2023-11-30 01:09:55 26 4
gpt4 key购买 nike

像这样的 C++ 行 Foo t3 = Foo::construct(true); 在默认构造函数是私有(private)的情况下如何工作?我的假设(这显然是不正确的)是调用默认构造函数,然后是我的赋值运算符。该假设一定是不正确的,因为默认构造函数是私有(private)的,无法调用。

一个具体的例子:

class Foo {
private:
Foo() {}
bool bar;
public:
Foo(bool t): bar(t) {}
static Foo construct(bool t) {
Foo temp; //calling private constructor;
temp.bar = t;
return temp;
}
}

实例化此类的测试方法如下所示:

int main() {
//Foo t1; //Not allowed, compile error, Foo() is private
Foo t2(true); //Constructor, valid use
Foo t3 = Foo::construct(true); //It works! Why?
return 0;
}

t3 被实例化时,幕后到底发生了什么?

最佳答案

Foo t3 = Foo::construct(true); //It works! Why?

因为这不是默认初始化后跟赋值,而是 copy initialization

1) when a named variable (automatic, static, or thread-local) of a non-reference type T is declared with the initializer consisting of an equals sign followed by an expression.

所以根据这个说法:

If T is a class type and the cv-unqualified version of the type of other is T or a class derived from T, the non-explicit constructors of T are examined and the best match is selected by overload resolution. The constructor is then called to initialize the object.

还有这个:

If other is an rvalue expression, move constructor will be selected by overload resolution and called during copy-initialization. There is no such term as move-initialization.

在您的案例中使用了隐式声明的移动构造函数。

关于c++ - 静态方法类实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39170931/

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