5

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.

2 Answers 2

5

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

const std::shared_ptr<A> A::INSTANCE { new A };
Sign up to request clarification or add additional context in comments.

2 Comments

I'm baffled. Why can't make_shared() use that approach (or why has it trouble with the visibility while this variant has not)? Anyway, it works, so thanks :-)
make_shared is defined outside your class, so it can't access a private constructor. But the initializer for a static member is considered part of the class definition, so it is able to access private members.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.