防止在对象的工厂方法外实例化 [英] Prevent instantiation of an object outside its factory method

查看:55
本文介绍了防止在对象的工厂方法外实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有工厂方法的类

Suppose I have a class with a factory method

class A {
public:
  static A* newA()
  {
    // Some code, logging, ...
    return new A();
  }
}

是否可以用 new 防止实例化此类的对象,所以工厂方法是创建对象实例的唯一方法?

Is it possible to prevent the instantiation of an object of this class with a new, so that factory method is the only method to create an instance of the object?

推荐答案

可以;只需将构造函数设为私有(如果这是基类,则对其进行保护):

Sure; just make the constructor private (protected if this is a base class):

class A {
public:
  static A* newA()
  {
    // Some code, logging, ...
    return new A();
  }

private:
  A() {}  // Default constructor
};

如果需要,还应将复制构造函数设置为私有/受保护的.

You should make the copy constructor private/protected as well, if required.

和往常一样,您应该强烈考虑返回智能指针而不是原始指针,以简化内存管理问题.

And as always, you should strongly consider returning a smart pointer rather than a raw pointer, in order to simplify memory management issues.

这篇关于防止在对象的工厂方法外实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆