在C ++中的单例模式 [英] Singleton pattern in C++

查看:117
本文介绍了在C ++中的单例模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于单例模式的问题。



我看到有关单例类中静态成员的两个情况。



首先它是一个对象,像这样

  class CMySingleton 
{
public:
static CMySingleton& Instance()
{
static CMySingleton单例;
return singleton;
}

//其他非静态成员函数
private:
CMySingleton(){} //私有构造函数
〜CMySingleton(){}
CMySingleton(const CMySingleton&); // Prevent copy-construction
CMySingleton& operator =(const CMySingleton&); //防止赋值
};

一个是指针,像这样

  class GlobalClass 
{
int m_value;
static GlobalClass * s_instance;
GlobalClass(int v = 0)
{
m_value = v;
}
public:
int get_value()
{
return m_value;
}
void set_value(int v)
{
m_value = v;
}
static GlobalClass * instance()
{
if(!s_instance)
s_instance = new GlobalClass;
return s_instance;
}
};

这两种情况有什么区别?哪一个是正确的?

解决方案

您应该可以阅读Alexandrescu的书。



关于本地静态,我没有使用Visual Studio一段时间,但当使用Visual Studio 2003编译时,有一个本地静态分配每个DLL ...谈论一个噩梦的调试,我会记得一段时间:/



1。单身人士的生命



单身人士的主要问题是终身管理。



尝试使用对象,你需要活着和踢。因此,问题来自于初始化和销毁​​,这是C ++中全局变量的常见问题。



初始化通常是最容易纠正的。正如这两种方法所建议的,它很简单,可以在初次使用时进行初始化。



破坏是一个更精致。全局变量以创建它们的相反顺序销毁。所以在本地静态情况下,你实际上不控制事情....



2。本地静态

  struct A 
{
A(){B :: Instance ); C :: Instance()。call(); }
};

struct B
{
〜B(){C :: Instance()。call(); }
static B& Instance(){static B MI;返回MI; }
};

struct C
{
static C& Instance(){static C MI;返回MI; }
void call(){}
};

A globalA;

这里有什么问题?让我们检查调用构造函数和析构函数的顺序。



首先,构建阶段:




  • 执行一个globalA; A :: A() >
  • A :: A()调用 B :: B()

  • A :: A()调用 C :: C()



它工作正常,因为我们初始化 B C 第一次访问时的实例。



其次,销毁阶段:




  • C ::〜C()被调用,因为它是最后一个构造的3

  • B ::〜B()被称为... oups,它尝试访问 C 的实例!



我们因此在破坏时具有未定义的行为,哼...



3。新策略



这里的想法很简单。全局内置函数在其他全局变量之前被初始化,所以你的指针将被设置为 0 ,然后才能调用任何你编写的代码, :

  S& S :: Instance(){if(MInstance == 0)MInstance = new S(); return * MInstance; } 

实际上会检查实例是否正确。



然而,一直说,这里有一个内存泄漏,最糟糕的是一个析构函数,从来没有被调用。解决方案存在,并且是标准化的。它是对 atexit 函数的调用。



atexit 函数允许您指定在程序关闭期间执行的操作。这样,我们可以写一个单例:

  // in s.hpp 
class S
{
public:
static S& Instance(); //已经定义

private:
static void CleanUp();

S(); //后来,因为这是工作发生的地方
〜S(){/ *什么? * /}

//不可复制
S(S const&);
S& operator =(S const&);

static S * MInstance;
};

// in s.cpp
S * S :: MInstance = 0;

S :: S(){atexit(& CleanUp); }

S :: CleanUp(){delete MInstance; MInstance = 0; } //注意= 0位!

首先,让我们进一步了解 atexit 。签名是 int atexit(void(* function)(void)); ,即它接受一个指向一个不带任何东西作为参数的函数的指针。 p>

其次,它是如何工作的?好吧,就像前面的用例:在初始化它建立一个指针的函数堆栈调用,在销毁它一次一个项目。因此,实际上,函数以后进先出方式被调用。



这里会发生什么?




  • 第一次访问时构造(初始化很好),我注册 CleanUp 方法退出时间

    / li>
  • 退出时间: CleanUp 方法被调用。它破坏对象(因此我们可以有效地在析构函数中工作)并将指针重置为 0 来发送信号。




如果(例如 A B C )我调用一个已经销毁的对象的实例?在这种情况下,由于我将指针指向 0 ,我将重建一个临时单例,循环重新开始。



Alexandrescu称它为 Phoenix Singleton



另一个选择是有一个静态标志,并将其设置为 destroyed 在清理过程中,让用户知道它没有得到单例的实例,例如通过返回一个空指针。返回一个指针(或引用)的唯一问题是,你最好希望没有人愚蠢到调用 delete :/



4。 Monoid模式



因为我们在谈论 Singleton c $ c> Monoid Pattern。实质上,它可以被视为 Flyweight 模式的退化情况,或者使用 Proxy over Singleton



Monoid 模式很简单:



我会借此机会揭露不是Phoenix的实现:)

  class Monoid 
{
public:
void foo(){if(State * i = Instance())i-> foo ; }
void bar(){if(State * i = Instance())i-> bar }

private:
struct State {};

static State * Instance();
static void CleanUp();

static bool MDestroyed;
static State * MInstance;
};

// .cpp
bool Monoid :: MDestroyed = false;
State * Monoid :: MInstance = 0;

State * Monoid :: Instance()
{
if(!MDestroyed&&!MInstance)
{
MInstance = new State );
atexit(& CleanUp);
}
return MInstance;
}

void Monoid :: CleanUp()
{
delete MInstance;
MInstance = 0;
MDestroyed = true;
}

有什么好处?它隐藏了一个事实,即状态是共享的,它隐藏了 Singleton




  • 如果你需要有两个不同的状态,你可能会设法做到这一点,而不改变每一行代码使用它(代替 Singleton 通过调用a Factory 例如)

  • Nodoby将在您的单身人士的电话上呼叫 delete 实例,所以你真正的管理状态,防止意外...你不能对恶意用户反对!

  • 你控制对单例的访问,所以,它已被销毁,您可以正确处理它(不做任何操作,记录等)



5。最后一个字



完成后,我想指出,我已经高兴地撇除了任何多线程问题...阅读Alexandrescu的现代C以了解更多信息!


I have a question about the singleton pattern.

I saw two cases concerning the static member in the singleton class.

First it is an object, like this

class CMySingleton
{
public:
  static CMySingleton& Instance()
  {
    static CMySingleton singleton;
    return singleton;
  }

// Other non-static member functions
private:
  CMySingleton() {}                                  // Private constructor
  ~CMySingleton() {}
  CMySingleton(const CMySingleton&);                 // Prevent copy-construction
  CMySingleton& operator=(const CMySingleton&);      // Prevent assignment
};

One is an pointer, like this

class GlobalClass
{
    int m_value;
    static GlobalClass *s_instance;
    GlobalClass(int v = 0)
    {
        m_value = v;
    }
  public:
    int get_value()
    {
        return m_value;
    }
    void set_value(int v)
    {
        m_value = v;
    }
    static GlobalClass *instance()
    {
        if (!s_instance)
          s_instance = new GlobalClass;
        return s_instance;
    }
};

What's the difference between the two cases? Which one is correct?

解决方案

You should probably read up Alexandrescu's book.

Regarding the local static, I haven't use Visual Studio for a while, but when compiling with Visual Studio 2003, there was one local static allocated per DLL... talk about a nightmare of debugging, I'll remember that one for a while :/

1. Lifetime of a Singleton

The main issue about singletons is the lifetime management.

If you ever try to use the object, you need to be alive and kicking. The problem thus come from both the initialization and destruction, which is a common issue in C++ with globals.

The initialization is usually the easiest thing to correct. As both methods suggest, it's simple enough to initialize on first use.

The destruction is a bit more delicate. global variables are destroyed in the reverse order in which they were created. So in the local static case, you don't actually control things....

2. Local static

struct A
{
  A() { B::Instance(); C::Instance().call(); }
};

struct B
{
  ~B() { C::Instance().call(); }
  static B& Instance() { static B MI; return MI; }
};

struct C
{
  static C& Instance() { static C MI; return MI; }
  void call() {}
};

A globalA;

What's the problem here ? Let's check on the order in which the constructors and destructors are called.

First, the construction phase:

  • A globalA; is executed, A::A() is called
  • A::A() calls B::B()
  • A::A() calls C::C()

It works fine, because we initialize B and C instances on first access.

Second, the destruction phase:

  • C::~C() is called because it was the last constructed of the 3
  • B::~B() is called... oups, it attempts to access C's instance !

We thus have undefined behavior at destruction, hum...

3. The new strategy

The idea here is simple. global built-ins are initialized before the other globals, so your pointer will be set to 0 before any of the code you've written will get called, it ensures that the test:

S& S::Instance() { if (MInstance == 0) MInstance = new S(); return *MInstance; }

Will actually check whether or not the instance is correct.

However has at been said, there is a memory leak here and worst a destructor that never gets called. The solution exists, and is standardized. It is a call to the atexit function.

The atexit function let you specify an action to execute during the shutdown of the program. With that, we can write a singleton alright:

// in s.hpp
class S
{
public:
  static S& Instance(); // already defined

private:
  static void CleanUp();

  S(); // later, because that's where the work takes place
  ~S() { /* anything ? */ }

  // not copyable
  S(S const&);
  S& operator=(S const&);

  static S* MInstance;
};

// in s.cpp
S* S::MInstance = 0;

S::S() { atexit(&CleanUp); }

S::CleanUp() { delete MInstance; MInstance = 0; } // Note the = 0 bit!!!

First, let's learn more about atexit. The signature is int atexit(void (*function)(void));, ie it accepts a pointer to a function that takes nothing as argument and returns nothing either.

Second, how does it work ? Well, exactly like the previous use case: at initialization it builds up a stack of the pointers to function to call and at destruction it empties the stack one item at a time. So, in effect, the functions get called in a Last-In First-Out fashion.

What happens here then ?

  • Construction on first access (initialization is fine), I register the CleanUp method for exit time

  • Exit time: the CleanUp method gets called. It destroys the object (thus we can effectively do work in the destructor) and reset the pointer to 0 to signal it.

What happens if (like in the example with A, B and C) I call upon the instance of an already destroyed object ? Well, in this case, since I set back the pointer to 0 I'll rebuild a temporary singleton and the cycle begins anew. It won't live for long though since I am depiling my stack.

Alexandrescu called it the Phoenix Singleton as it resurrects from its ashes if it's needed after it got destroyed.

Another alternative is to have a static flag and set it to destroyed during the clean up and let the user know it didn't get an instance of the singleton, for example by returning a null pointer. The only issue I have with returning a pointer (or reference) is that you'd better hope nobody's stupid enough to call delete on it :/

4. The Monoid Pattern

Since we are talking about Singleton I think it's time to introduce the Monoid Pattern. In essence, it can be seen as a degenerated case of the Flyweight pattern, or a use of Proxy over Singleton.

The Monoid pattern is simple: all instances of the class share a common state.

I'll take the opportunity to expose the not-Phoenix implementation :)

class Monoid
{
public:
  void foo() { if (State* i = Instance()) i->foo(); }
  void bar() { if (State* i = Instance()) i->bar(); }

private:
  struct State {};

  static State* Instance();
  static void CleanUp();

  static bool MDestroyed;
  static State* MInstance;
};

// .cpp
bool Monoid::MDestroyed = false;
State* Monoid::MInstance = 0;

State* Monoid::Instance()
{
  if (!MDestroyed && !MInstance)
  {
    MInstance = new State();
    atexit(&CleanUp);
  }
  return MInstance;
}

void Monoid::CleanUp()
{
  delete MInstance;
  MInstance = 0;
  MDestroyed = true;
}

What's the benefit ? It hides the fact that the state is shared, it hides the Singleton.

  • If you ever need to have 2 distinct states, it's possible that you'll manage to do it without changing every line of code that used it (replacing the Singleton by a call to a Factory for example)
  • Nodoby's going to call delete on your singleton's instance, so you really manage the state and prevent accidents... you can't do much against malicious users anyway!
  • You control the access to the singleton, so in case it's called after it's been destroyed you can handle it correctly (do nothing, log, etc...)

5. Last word

As complete as this may seem, I'd like to point out that I have happily skimmed any multithread issues... read Alexandrescu's Modern C++ to learn more!

这篇关于在C ++中的单例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆