Private C ++ Constructors

If I do not want to allow anyone to create an instance of my class other than my static functions (I think this is called singleton / factory?), Is it enough to make it the default constructor or to do it? I also need to explicitly define and make the copy constructor and operator private assignment?

+3
source share
4 answers

Yes, I would do all 3 of these manager functions. If not, you do not want to have access to 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 &);
};
+2
source

constuctor private factory. singleton factory.
boost , , , , , , . , , , , .

+3

, . , :

MyClass newObject = your_singleton_of_type_MyClass;

, . , .

0

If you need only one instance, then yes, the copy constructor should be private. The assignment operator should not matter because it will be impossible to use.

0
source

Source: https://habr.com/ru/post/1772952/


All Articles