Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton example in C++/CLI?

I've looked around, I need an example for Singleton class that works across 2 or more C++/CLI files.

How do you declare a singleton in C++/CLI, not C# ?

How do you share that singleton across two or more C++/CLI files?

I keep getting Variable redefinitions when I try to share that singleton.

like image 418
buttercup Avatar asked Jul 15 '10 18:07

buttercup


People also ask

What is a singleton in C?

Singleton in C++ Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Singleton has almost the same pros and cons as global variables. Although they're super-handy, they break the modularity of your code.

How do you declare a singleton class in C#?

Singleton Class allow for single allocations and instances of data. It has normal methods and you can call it using an instance. To prevent multiple instances of the class, the private constructor is used.

Is singleton thread safe C++?

The beauty of the Meyers Singleton in C++11 is that it's automatically thread-safe. That is guaranteed by the standard: Static variables with block scope. The Meyers Singleton is a static variable with block scope, so we are done.


1 Answers

This is for C++/CLI, not ".NET Managed Extensions for C++" aka C++.NET. Don't use the Managed Extensions (Visual Studio 2002-2003), they're buggy.

ref class Singleton
{
private:
  Singleton() {}
  Singleton(const Singleton%) { throw gcnew System::InvalidOperationException("singleton cannot be copy-constructed"); }
  static Singleton m_instance;

 public:
  static property Singleton^ Instance { Singleton^ get() { return %m_instance; } }
};

As for "across multiple files", other compilation units in the same project use #include, other assemblies use a reference (or #import). Then there won't be any redefinition issues.

like image 190
Ben Voigt Avatar answered Feb 08 '23 17:02

Ben Voigt