静态方法class实例化

Static method class instantiation

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

一个具体的例子:

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;
   }
}

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

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 时幕后究竟发生了什么?

您的行没有调用默认构造函数或复制赋值运算符。

它从 construct 返回的临时对象复制构造 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.

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

静态构造方法属于class,可以访问私有构造函数——这在实现工厂模式时经常使用。