开发者

c++ private constructors

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 开发者_如何学Pythonmake private a copy constructor and assignment operator?


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.


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:

Singleton * s;
Singleton copy( *s );

So do something like:

class Singleton
{
private:
  Singleton();
  Singleton(const Singleton &);
  Singleton & operator = (const Singleton &);
};


Yes, usually you have to. If not, you could construct a new object by copy:

MyClass newObject = your_singleton_of_type_MyClass;

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜