c++私有构造函数
如果我不想允许任何人创建我的类的实例,除了我的静态函数(我认为这称为单例/工厂?),是否足以将默认构造函数设为私有,或者我还需要显式地定义并私有复制构造函数和赋值运算符?
If I don't want to allow anyone to create an instance of my class except for my static functions (I think this is called singleton/factory?), is it enough to make the default constructor private, or do I also need to explicitly define and make private a copy constructor and assignment operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将构造函数设为私有是为了工厂方法模式。单例模式需要工厂方法。
如果您不希望您的类被复制,则 boost 具有不可复制的功能,但正如 James McNellis 已经评论的那样:决定用户是否应该能够复制该类。由于原始指针和固有的内存管理不应再在类中占有一席之地,因此复制类的问题主要针对使用资源或可能大型容器的类。
Making the constuctor private is for the factory method pattern. The singleton pattern needs a factory method.
boost has noncopyable if you don't want your class to be copied, but as James McNellis already commented: decide whether users should be able to copy the class. Because raw pointers and the inherent memory management should not have a place in classes anymore, the question of having classes copied is mostly for classes that use resources or possibly large containers.
是的,我会履行所有 3 个经理职能。如果不是,您不希望能够访问复制构造函数。例如,这是有效的:
因此请执行以下操作:
Yes, I would do all 3 of those manager functions. If not, you do not want to be able to access the copy constructor. For example, this is valid:
So do something like:
是的,通常你必须这样做。如果没有,您可以通过复制构造一个新对象:
在这种情况下,发出复制构造函数,实际上创建两个对象。将复制构造函数设置为私有可以通过使此代码非法来防止复制。
Yes, usually you have to. If not, you could construct a new object by copy:
In this case the copy constructor is issued, creating two objects actually. Making the copy constructor private prevents the copy by making this code illegal.
如果您只想要一个实例,那么是的,复制构造函数应该是私有的。赋值运算符应该不重要,因为无论如何它都无法使用。
If you only want one instance, then yes, the copy constructor should be private. The assignment operator shouldn't matter, because it will be impossible to use anyway.