我们什么时候需要 C++ 中的私有构造函数?

2021-12-30 constructor private c++

我有一个关于 C++ 中私有构造函数的问题.如果构造函数是私有的,我如何创建类的实例?

I have a question about private constructors in C++. If the constructor is private, how can I create an instance of the class?

我们应该在类内部有一个 getInstance() 方法吗?

Should we have a getInstance() method inside the class?

推荐答案

private 构造函数有几种情况:

There are a few scenarios for having private constructors:

  1. 限制除friend以外的所有对象的创建;在这种情况下,所有构造函数都必须是 private

  1. Restricting object creation for all but friends; in this case all constructors have to be private

class A
{
private:
   A () {}
public:
   // other accessible methods
   friend class B;
};

class B
{
public:
   A* Create_A () { return new A; }  // creation rights only with `B`
};

  • 限制特定类型的构造函数(即复制构造函数、默认构造函数).例如std::fstream 不允许通过这种不可访问的构造函数进行复制

  • Restricting certain type of constructor (i.e. copy constructor, default constructor). e.g. std::fstream doesn't allow copying by such inaccessible constructor

    class A
    {
    public:
       A();
       A(int);
    private:
       A(const A&);  // C++03: Even `friend`s can't use this
       A(const A&) = delete;  // C++11: making `private` doesn't matter
    };
    

  • 要有一个公用的委托构造函数,不应该暴露给外部世界:

  • To have a common delegate constructor, which is not supposed to be exposed to the outer world:

    class A
    {
    private: 
      int x_;
      A (const int x) : x_(x) {} // common delegate; but within limits of `A`
    public:
      A (const B& b) : A(b.x_) {}
      A (const C& c) : A(c.foo()) {}
    };
    

  • 对于 单例模式,当单例 class 不可继承时(如果是可继承然后使用 protected 构造函数)

  • For singleton patterns when the singleton class is not inheritible (if it's inheritible then use a protected constructor)

    class Singleton
    {
    public:
       static Singleton& getInstance() {
          Singleton object; // lazy initialization or use `new` & null-check
          return object;
       }
    private:
       Singleton() {}  // make `protected` for further inheritance
       Singleton(const Singleton&);  // inaccessible
       Singleton& operator=(const Singleton&);  // inaccessible
    };
    

  • 相关文章