All,
I am using C++14 and am making a more-or-less standard Singleton. I am using the latest Visual Studio 2017. This code works:
#include <memory>
class A
{
public:
static A& getInstance()
{
if (instance == nullptr)
instance = std::unique_ptr<A>(new A());
return *instance;
}
private:
A() {}
static std::unique_ptr<A> instance;
};
std::unique_ptr<A> A::instance = nullptr;
However, when I change the creation of the singleton instance to this:
instance = std::make_unique<A>();
I get a compilation error that I am trying to access a private member:
Error C2248 'A::A': cannot access private member declared in class 'A'
c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.14.26428\include\memory 2510
This feels like a bug to me, as the two forms should be identical in function? Thoughts?
The purpose of std::unique_ptr<> is to control the lifetime of the object pointed to. You may pass a std::unique_ptr<> around, but that will also transfer ownership of the object pointed to. This concept does not match very well with the concept of a singleton. There is only one place that is ever allowed to create (or delete) the singleton. You don't really need a std::unique_ptr<>for that. As already said in the comments, there are simpler ways for that. I would prefer #Praetorian's suggestion:
static A& getInstance()
{
static A instance;
return instance;
}
The reason why you can't use std::make_unique<>() to instantiate your class is that the constructor is private. To access it, you need the accessing function to be a friend. Have a look at How to make std::make_unique a friend of my class for that. Another solution is to provide a public constructor requiring a private type as argument, as described int this solution.
instance = std::make_unique<A>();
this creates the A within the function make_unique. But the ctor you want to call is private.
private:
struct ctor_permission_t{
explicit ctor_permission_t(int){};
};
public:
explicit A(ctor_permission_t):A(){}
};
then
instance = std::make_unique<A>(ctor_permission_t{0});
The ctor_permission_t acts as a token giving its possessor the right to construct an A. We pass this to make_unique.
The explicit int ctor in ctor_permission_t makes it impossible to create it without naming the type, and only within instances and friends of A can name it because it is private. This makes it difficult to bypass this permission token.
To sum up the others answers' and fix some flaws in them:
You can make a private structure with a private constructor which is a friend with your class. Then make your class constructor public but with an additional argument of that private structure.
Also its better to use static function witch return a reference instead of the bare static variable.
#include <memory>
class A
{
struct Private
{
friend A;
private:
explicit Private() = default;
};
public:
static A * getInstance()
{
if (!instance())
instance() = std::make_unique<A>(Private());
return instance();
}
A(Private) {};
private:
static std::unique_ptr<A> & instance()
{
static std::unique_ptr<A> inst;
return inst;
}
};
Or if you really dont need any special configurations which requires using a pointer and heap allocation (like initializing the instance in a special thread or ...) :
class A
{
public:
static A & getInstance()
{
static A instance;
return instance;
}
private:
A() = default;
};
Related
I have a question about private constructors in C++. If the constructor is private, how can I create an instance of the class?
Should we have a getInstance() method inside the class?
There are a few scenarios for having private constructors:
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`
};
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()) {}
};
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
};
A private constructor is commonly used with Builder methods, for example in the Named Constructor idiom.
class Point
{
public:
static Point Polar(double, double);
static Point Cartesian(double, double);
private:
Point(double,double);
};
In this (typical) example, the Named Constructor idiom is used to make it explicitly which coordinate system is used to build the Point object.
A private constructor is useful when you want to control the object creation of a class.
Let’s try in code:
#include <iostream>
using namespace std;
class aTestClass
{
aTestClass() ////////// Private constructor of this class
{
cout << "Object created\n";
}
public:
};
int main()
{
aTestClass a;
aTestClass *anObject;
}
The line aTestClass a causes an error because this line is indirectly trying to access the private constructor. Comment out this line and run the program. It runs absolutely fine. Now the question is how to create the object in a such case. Let's write another program.
#include <iostream>
using namespace std;
class aTestClass
{
aTestClass() ////////// Private constructor of this class
{
cout << "Object created\n";
}
public:
aTestClass* getAnObject() ///// A public method create an object of this class and return the address of an object of that class
{
return (new aTestClass);
}
};
int main()
{
//aTestClass a;
aTestClass *anObject = NULL;
anObject = anObject->getAnObject();
}
The output is
Object created
so we have created an object of the class containing a private constructor.
Use this concept to implement a singleton class
Yes, this is commonly used in the Singleton pattern where the object is accessed through a static member function.
If some constructor is private, it means that no one but the class itself (and friends) should be able to create instances of it using that constructor. Therefore, you can provide static methods like getInstance() to create instances of the class or create the instances in some friend class/method.
It depends on why the constructor was made private in the first place (you should ask whoever wrote the class you are editing). Sometimes a constructor may be made private to disallow copy construction (while allowing construction through some other constructor). Other times a constructor may be made private to disallow creating the class except by the class's "friend"s (this is commonly done if the class is a "helper" that should only be used by the class(es) for which the helper class was created). A constructor may also be made private to force the use of a (usually static) creation function.
If you create a private constructor you need to create the object inside the class
#include<iostream>
//factory method
using namespace std;
class Test
{
private:
Test(){
cout<<"Object created"<<endl;
}
public:
static Test* m1(){
Test *t = new Test();
return t;
}
void m2(){
cout<<"m2-Test"<<endl;
}
};
int main(){
Test *t = Test::m1();
t->m2();
return 0;
}
A private constructor in C++ can be used for restricting object creation of a constant structure. And you can define a similar constant in the same scope like enum:
struct MathConst{
static const uint8 ANG_180 = 180;
static const uint8 ANG_90 = 90;
private:
MathConst(); // Restricting object creation
};
Access it like MathConst::ANG_180.
We are in the process of deprecating ACE libraries in our project which consists of around 120 binaries and in many of binaries we have used ACE_Singleton.Since after deprecating we will not have this class so we are thinking of writing our own generic singleton in our shared library that is common across all these binaries and one of the goals that we want to achieve is if somebody inherit from this class (using CRTP) say Logger and even when Logger constructor is public then also we cannot create two logger object.
To illustrate let's assume my singleton class name is GenericSingleton and my client class is logger then following code should throw error :
class Logger:public GenericSingleton<Logger>
{
public:
Logger()
{
}
};
int main()
{
Logger obj;// first instance no issue
Logger obj1; // second instance is problem as it is inherited from singleton
}
So can somebody suggest me how GenericSingleton should be designed so that while creating second object i should get compiletime error ?
In short is there a way that if my derived class doesn't have private constructor,destructor copy constructor etc. then it can be checked at compiletime using static_assert ?
There's no way for a constructor to know at compile time where or how many times it will be called; constructors are just functions, and functions don't know anything about their contexts. Consider that any static_asserts will be evaluated when the class is compiled, but this can (and almost certainly will!) happen in an entirely different translation unit from code that actually instantiates the class.
In any case, it seems unlikely that this would be helpful, because you must have some way to access singletons throughout your codebase.
Additionally, it's unclear why you want to permit your singletons to have public constructors. If you want to enforce singleton behavior at compile time for a completely arbitrary class just by adding an inheritance declaration, you're out of luck; arbitrary classes can be, well, arbitrarily constructed.
Since you're transitioning from the ACE singleton, I suggest you use a similar API; note that the ACE singleton documentation recommends making your singleton constructors private.
If, however, you just want some way to force your client to write a constructor that can't (easily) be called improperly, you can do something like this:
template <typename T>
class SingletonBase {
protected: class P { friend class SingletonBase<T>; P() = default; };
public:
SingletonBase(P) {}
static T& Instance() {
static T instance { P {} };
return instance;
}
};
(You will also need to delete the base class's copy and move constructors. Here is a working example use case. Note that declaring P's constructor =default does not prevent the singleton class from default-initializing instances of P. )
Now, because the base class constructor takes an argument of type P, the singleton class implementation must pass a P to its parent class constructor. But since the constructor for P is private, the singleton class won't be able to construct an instance of P except by copy or move construction, so its constructor must take an instance of P. But since P itself is protected, only the singleton class and the parent class can actually use it, so effectively the only possible call to the child's constructor must be in the Instance method.
Note that you do not need to explicitly declare and define the singleton-class's constructor, which would be ugly because of the need to use SingletonBase<Singleton>::P. You can simply expose the constructor with a using declaration:
using BASE = SingletonBase<Myclass>;
using BASE::SingletonBase;
You need to make sure that instances of Logger cannot be created outside the function that creates the sole instance of Logger.
Here's a simple implementation.
template <typename T> class GenericSingleton {
public:
static T& instance() {
static T instance_;
return instance_;
}
};
class Logger: public GenericSingleton<Logger>
{
// Make sure that the base class can create the sole instance of
// this class.
friend GenericSingleton<Logger>;
private:
// Makes sure that you cannot create objects of the class
// outside GenericSingleton<Logger>
~Logger() {}
public:
void foo() {}
};
int main()
{
// OK. Call foo() on the only instance of the class.
Logger::instance().foo();
// Not OK.
Logger obj1;
}
My advice would be to separate concerns. There is the concept of a service (such as a logger) and the service may or may not be a singleton. But this is an implementation detail, and therefore a separate concern. The consumer of the service ought to be agnostic of it.
Now, later in the lifecycle of the project, when you realise that singletons were a terrible idea, you can refactor the singleton without having to refactor any code that depends on it.
e.g.:
template<class Impl>
struct implements_singleton
{
using impl_type = Impl;
static impl_type& get_impl()
{
static impl_type _{};
return _;
}
};
struct logger_impl
{
void log_line(std::string const& s)
{
std::clog << s << std::endl;
}
};
struct logger
: private implements_singleton<logger_impl>
{
void log_line(std::string const& s) {
get_impl().log_line(s);
}
};
void do_something(logger& l)
{
l.log_line("c");
}
int main()
{
logger a;
logger b;
a.log_line("a");
b.log_line("b"); // behind the scenes this is the same logger
// but the user need not care
do_something(a);
}
My Base class is Singleton having protected c'tor. Now, I can derive another class from it but I cannot create instance of that Base class inside functions of derived class. This is expected behavior as per my design. But I like to know is it correct by C++ standards or just my compiler specific behavior? (So that I shouldn't face issues if I want to port this code in future)
class Singleton
{
protected:
Singleton() {}
public:
Singleton * GetInstance()
{
static Singleton* InstanceCreated = NULL ;
if (!InstanceCreated)
InstanceCreated = new Singleton ;
return InstanceCreated ;
}
};
class Deringlton : public Singleton
{
public:
Deringlton()
{
Singleton * pSing ;
// pSing = new Singlton ; // Cannot create object of singlton
// (Despite class is derived from singlton)
}
};
I think a better way to provide a generic singleton implementation is to use the CRTP and directly inheriting from that template. That means every class automagically implements the singleton pattern only inheriting from the CRTP base:
template<typename DERIVED>
class generic_singleton
{
private:
static DERIVED* _instance;
static void _singleton_deleter() { delete _instance; } //Function that manages the destruction of the instance at the end of the execution.
protected:
generic_singleton() {}
virtual ~generic_singleton() {} //IMPORTANT: virtual destructor
public:
DERIVED& instance() //Never return pointers!!! Be aware of "delete Foo.instance()"
{
if(!_instance)
{
_instance = new DERIVED;
std::atexit( _singleton_deleter ); //Destruction of instance registered at runtime exit (No leak).
}
return static_cast<DERIVED&>( _instance );
}
};
template<typename DERIVED>
DERIVED* generic_singleton<DERIVED>::_instance = nullptr;
The memory release is provided by registering a function that does the delete at the end of the application, with std::ateexit().
What's the point of having a pointer an not just a static variable?
class Singleton
{
public:
static Singleton& instance()
{ static Singleton z; return z; }
private:
Singleton() {}
~SIngleton() {}
};
In don't see any value in deriving it.
If you want to make this pattern coded as a template you can do
template<class S>
S& instance_of() { static S z; return z; }
and make instance_of<yourclass>() a friend of yourclass, having private ctor / dtor.
The use of a static variable makes the object granted to be properly constructed and destructed. (Unlike a remaining leaked pointer, with no destructor call...)
If you have to make a singleton (which you should avoid) the instance and(!) the declaration are a singleton. You could use a template have a 'generic' one, but inheritance is no good.
This is expected behaviour. The rule is you can only access protected members in Deringlton if the pointer is of type Deringlton. You cannot access protected members through a pointer of type Singleton. For example:
Deringlton* d = this;
d->someProtectedMethod(); // OK!
Singleton* s = this;
s->someProtectedMethod(); // Will fail
Since accessing new Singleton is not through a Deringlton pointer, it is not allowed. You can only access it through Deringlton by doing new Deringlton.
This behavior is specified in the standard.
Section 11.4 [class.protected] of C++11 states (emphasis mine):
As described earlier, access to a protected member is granted because
the reference occurs in a friend or member of some class C. If the
access is to form a pointer to member (5.3.1), the
nested-name-specifier shall denote C or a class derived from C. All
other accesses involve a (possibly implicit) object expression
(5.2.5). In this case, the class of the object expression shall be C
or a class derived from C.
What this means is that access to the base constructor is granted only if you are creating an object of the derived class. So for example, this would compile:
Deringlton()
{
Deringlton* p = new Deringlton();
}
I like to experiment around as I learn more about coding. I have a program that would only require a single instance of a struct for the life of it's runtime and was wondering if it's possible to create a singleton struct. I see lot's of information on making a singleton class on the internet but nothing on making a singleton struct. Can this be done? If so, how?
Thanks in advance. Oh, and I work in C++ btw.
A class and a struct are pretty much the same thing, except for some minor details (such as default access level of their members). Thus, for example:
struct singleton
{
static singleton& get_instance()
{
static singleton instance;
return instance;
}
// The copy constructor is deleted, to prevent client code from creating new
// instances of this class by copying the instance returned by get_instance()
singleton(singleton const&) = delete;
// The move constructor is deleted, to prevent client code from moving from
// the object returned by get_instance(), which could result in other clients
// retrieving a reference to an object with unspecified state.
singleton(singleton&&) = delete;
private:
// Default-constructor is private, to prevent client code from creating new
// instances of this class. The only instance shall be retrieved through the
// get_instance() function.
singleton() { }
};
int main()
{
singleton& s = singleton::get_instance();
}
Struct and class are in C++ almost the same (the only difference is default visibility of members).
Note, that if you want to make a singleton, you have to prevent struct/class users from instantiating, so hiding ctor and copy-ctor is inevitable.
struct Singleton
{
private:
static Singleton * instance;
Singleton()
{
}
Singleton(const Singleton & source)
{
// Disabling copy-ctor
}
Singleton(Singleton && source)
{
// Disabling move-ctor
}
public:
Singleton * GetInstance()
{
if (instance == nullptr)
instance = new Singleton();
return instance;
}
}
Conceptually, a struct and a class are the same in C++, so a making singleton struct is the same as making a singleton class.
The only difference between class and struct are the default access specifiers and base class inheritance: private for class and public for struct. For example,
class Foo : public Bar
{
public:
int a;
};
is the same as
struct Foo : Bar
{
int a;
};
So, there is no fundamental difference when it comes to singletons. Just make sure to read about why singletons are considered bad.
Here's a simple implementation:
struct singleton
{
static singleton& instance()
{
static singleton instance_;
return instance_;
}
singleton(const singleton&)=delete; // no copy
singleton& operator=(const singleton&)=delete; // no assignment
private:
singleton() { .... } // constructor(s)
};
First off, struct and class only refer to the default access of members. You can do everything with a struct that you can do with a class. Now if you were referring to POD structs, things get more complicated. You can't defined a custom constructor, so there's no way to enforce only a single object creation. However, there's nothing stopping you from simply only instantiating it once.
class and struct is almost a synonyms in C++. For singleton use case they are complete synonyms.
Is it compulsory to have a private destructor for a singleton class.
If the singleton is implemented as a variable at global scope, it must have a public destructor. Only public members are accessible at global scope.
If it's declared as a static member or static local within its own class, then the destructor may be private. The destructor is called from within class scope, where it is accessible, when the program exits. That is one way to enforce the object being a singleton. Do you need to strongly enforce that? If so, yes. It depends what you mean by "compulsory."
class A{
private:
~A() {}
public:
static A &getGlobalA() {
static A a2; // <- or here - better technique
return a2; // this is initialized upon 1st access
}; // and destroyed on program exit
static A a; // <- constructor, destructor accessed from here
};
A A::a; // <- but "called" from here in terms of control flow
This might not be what you are looking for.. But for reference, I use it as follows:
// .h
class Foo {
public:
static Foo* getInstance();
static void destroy();
private:
Foo();
~Foo();
static Foo* myInstance;
};
// .cpp
Foo* Foo::myInstance = NULL;
Foo* Foo::getInstance(){
if (!myInstance){
myInstance = new Foo();
}
return myInstance;
}
void Foo::destroy(){
delete myInstance;
myInstance = NULL;
}
Then at the end of my program, I call destroy on the object. As Péter points out the system will reclaim the memory when your program ends, so there is no real reason. The reason I use a destroy is when Ogre complained that I hadn't released all the memory I allocated. After that I just use it as "good manner", since I like cleaning up after myself.
In my opinion, the destructor of a signleton should be private. Otherwise somewone is able to call 'delete' for your singleton instance. I know, normally nobody will do it. But if we talk about excellence design, it must be resistant to all possible intended or unitnended damages.
With the modern C++ it is allowed to declare even private destructors for statically constructed objects.
Here is my code snippet for Singleton:
class Singleton
{
public:
static Singleton& GetInstance();
// Before C++ 11
private:
Singleton() {}
~Singleton() {}
Singleton(const Singleton&); // Without implementation
Singleton& operator=(const Singleton&); // Without implementation
// Since C++ 11
private:
Singleton() = default;
~Singleton() = default;
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
Singleton& Singleton::GetInstance()
{
static Singleton instance;
return instance;
}
All classes have a destructor. If you don't create one the compiler will do so for you. So your question can be reworded to: Does the destructor for a singleton class have to private?
The simple answer is no, it doesn't have to be.
A more interesting question: Is it a good idea to make the destructor of a singleton class private?
Yes, in general, it is a good idea. If you make it private then your client code won't call the destructor by accident. Calling the destructor would cause the singleton to fail for all clients as the instance would become invalid.
No, and in general objects in C++ are not given private destructors. Keep in mind that Singleton means that there is only one instance, and so it is construction, not destruction, that needs to be controlled / prevented. Usually a singleton has a private constructor, a public destructor, a private static instance variable, and a public static singleton get / lazy construction function, although there are variations on that pattern.
You may return reference to your singleton instance.
class Factory : public IFactory
{
private:
/**
* This class should not be instantiated through its constructor. Since, it implements
* Singleton pattern.
*/
Factory();
public:
virtual ~Factory();
/**
* Accessor method for singleton instance.
* \note use this static method to access to operations of this class.
*/
static IFactory& instance(){
if(!m_instance.get()){
m_instance.reset(new Factory());
}
return static_cast<IFactory&>(*m_instance);
}
/**
* \see IFactory::create
*/
virtual boost::shared_ptr<IConnector> create();
private:
/* Singleton instance */
static boost::scoped_ptr<Factory> m_instance;
};
Having a private destructor as part of a singleton is not required from a programmer's point of view, but essential from a design point of view.
It avoids misuse of the class.
However, if you add a private destructor, you have to instantiate your class:
In a function / method: because if you create it as a global variable, you lose the interest of using a singleton (created to avoid global variables).
With the correct way to instantiate it: if your destructor is private, your class could not be deleted at the end of your program if you instantiate it as a "classic" local variable, because it can't access to it. So you have to instantiate it like this :
Singleton * potatoe = &Singleton::getInstance();
Here, we create a weak pointer named "potatoe", wich correspond to the address of the result of the "getInstance" function.
The consequence is that the destructor will not be called at the end of the function. But because (in "getInstance") the variable is declared "static" in a "static" method, the destructor will be called at the end of the program, without you having to do it.
Here is my code. Feel free to comment it.
// "class.hpp" file
class Singleton {
public:
static Singleton& getInstance() {
static Singleton S;
return S;
}
private:
Singleton();
~Singleton();
};
// "main.cpp" file
#include "class.hpp"
int main()
{
Singleton * patatoe = &Singleton::getInstance();
Singleton * tomatoe = &Singleton::getInstance();
Singleton * salad = &Singleton::getInstance();
return 0;
}