Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static initialization with private constructor

Tags:

c++

In a class I have a static member that represents the singleton instance of that class:

class A {
public:
  static const std::shared_ptr<A> INSTANCE;
private:
  A();
};

In order to prevent more instances I made the constructor private. Now I have trouble to initialize the static var, because the initializer cannot access a private member. Here's the code I use in the .cpp file:

const std::shared_ptr<A> A::INSTANCE = std::make_shared<A>();

A factory method wouldn't help either, as it would have to be public as well. What else can I do to make this work? Note: I'd like to avoid the typical static get() method if possible.

like image 625
Mike Lischke Avatar asked Apr 24 '16 15:04

Mike Lischke


1 Answers

You can't use make_shared, but you can just create the instance directly:

const std::shared_ptr<A> A::INSTANCE { new A };
like image 77
Alan Stokes Avatar answered Sep 23 '22 13:09

Alan Stokes