Page 1 of 1

Singleton Pattern alternative in VC++ A simple singleton pattern in Visual C++ Rate Topic: -----

#1 David.Mott  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 4
  • Joined: 14-September 10

Posted 14 September 2010 - 02:02 PM

Singltons are a very common design pattern which ensures one and only one instance of an object exists in an app.

Most patterns rely on protected constructors anda static method and/or static instance variable declared in an implementation file. This route is portable and allows for good control of the object's creation, but I've always disliked the extra repeated calls to get the singleton's instance, and, in many cases, the additional implementation file in the project. While the compiler will generally optimize away the extra call instructions, it will not optimize away the extra code in the implementation that my eye must read.

Another route is to declare an instance of the class within the class declaration which has the same name as the class:

class Singleton{

Line 5 is a little used instance declaration. When the instance declaration is identical to the class name no further instances can be created on the stack or with the new operator and the instance is accessible by the class name:

int main(){
	Singleton oSingleton();
	Singleton * p = new Singleton();

Both lines 2 and 3 will cause syntax errors because the class type has been declared as an instance. This will effectively prevent the class from becoming instantiated again. If you've ever tried to create a global singleton in this manner and placed the declaration in a header file used by multiple implementation files, the linker will issue a duplicate defined symbol error. A way around this is to use the Visual C++ directive __declspec(selectany). This instructs the linker that a symbol maybe defined more than once in different compilation units and to discard all but 1 copy:

__declspec(selectany) class Singleton{

I define this directive as SINGLETON to clarify the class is also an instance:

#define SINGLETON __declspec(selectany)
SINGLETON class Singleton{

Creating a singleton in this way relies on the compiler's generated initialization code to construct the object which occurs before your app's main() function, which is therefore not within the developer's try and catch blocks. There is also no (direct/portable) way to handle the order in which multiple singletons are created. (I'll try to write a future tutorial on Visual C++ initialization to cover this in greater detail.)

Is This A Good Question/Topic? 0
  • +

Page 1 of 1