2

How can I create a singleton class in C++/CX?

James McNellis
  • 348,265
  • 75
  • 913
  • 977
lizhecome
  • 61
  • 1
  • 5
  • @DirkEddelbuettel - the OP is asking about C++/CX, which might have some different implications (I never heard of C++/CX before, but it is a new Microsoft extension to C++) – Attila May 22 '12 at 01:55
  • @Attila: Thanks, with that my comment is inappropriate and has been withdrawn. – Dirk Eddelbuettel May 22 '12 at 02:08

2 Answers2

5

First, consider whether you really need a singleton.

There's no real difference in how one implements a singleton in C++/CX as opposed to ordinary C++. You need to do two things: (1) prevent construction of multiple instances, and (2) provide access to a single, global instance of the object.

Here's a trivial example:

namespace Component
{
    public ref class Singleton sealed
    {
    public:

        static property Singleton^ Instance
        {
            Singleton^ get()
            {
                static Singleton^ instance = ref new Singleton();
                return instance;
            }
        }

    private:

        Singleton() { }
    };
}

I've used a local static variable for the singleton instance, to avoid namespace-scope static initialization ordering issues. Visual C++ does not yet support C++11's thread-safe static initialization, so if you may be using the single instance from multiple threads, either you'll want to consider using a namespace-scope static variable and working through any potential initialization ordering issues, or you'll need to investigate synchronizing the initialization.

Community
  • 1
  • 1
James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • Thanks, I've been trying to use the typical C# approach and have used up like 16 WTFs trying to get the initialization to work... :) – Filip Skakun Feb 13 '14 at 00:38
  • For anyone from the future wondering the same as Trevor, C++/CX provides Windows specific extensions to C++. The carets represent reference counted pointers. – Joshua W May 28 '19 at 02:22
0

The way I do this is to have a static variable for a pointer to your singleton class initialized to NULL and a private constructor. Then use a static Create(...) method to build an instance. In the static Create method check the static variable and only build an instance if its NULL

class Foo
{
  public:
    Foo* Create();
  private:
    Foo(); //private ctor
    static Foo* M_ClassDataP;
};

Foo* Foo::M_ClassDataP = NULL; //initialize class data ptr to null

Foo* Foo::Create()
{
    if (NULL != M_ClassDataP)
    {
        M_ClassDataP = new Foo();
    }
    return M_ClassDataP;
}