Mike Lischke
Mike Lischke

Reputation: 53317

Static initialization with private constructor

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.

Upvotes: 5

Views: 1623

Answers (2)

Alan Stokes
Alan Stokes

Reputation: 18964

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

const std::shared_ptr<A> A::INSTANCE { new A };

Upvotes: 5

orip
orip

Reputation: 75427

The initialization of a static member is unrelated to the constructor, so the global statement is indeed the right way to go. Is it not working for you?

EDIT: I just realized you're trying to avoid using a singleton access method for some reason. Sounds suspiciously like the Borg pattern. :) Unrelated to you r specific question but I'd advise you to reconsider.

Upvotes: 0

Related Questions