CWinApp如何实现单例模式? [英] how CWinApp does realize the singleton pattern?

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

问题描述

通常,单例模式是通过ctor为私有并提供名为getInstance的成员函数的方式应用的,但是CWinApp的实例被定义为全局对象,而其ctor不是私有的.因此MFC如何实现CWinApp的单例模式?

Generally,singleton pattern is applied by the way that the ctor is private and gives a member funtion named getInstance, but CWinApp''s instance is defined as a global object,its ctor is not private.So how does MFC realizes the singleton pattern for CWinApp?

推荐答案

MFC 不能将CWinApp作为单例实现,只是每个应用程序仅实例化该类的一个对象,但是如果您在代码中写了这样的内容:

MFC does not implement CWinApp as a singleton, simply each application instantiate just one object of that class, but if you write something like this in your code:

CWinApp theApp1;
CWinApp theApp2;



您获得了CWinApp



You obtain two different instances of CWinApp


的两个不同实例,因为Sauro Viti说CWinApp不是单例类.
声明CWinApp类的对象时,MFC将第一个对象存储到afxCurrentWinApp veriable.
请记住,MFC项目还具有WinMain(...)函数.

我们可以看到在声明对象CWinApp theApp1时会发生什么;

1)它将调用CWinApp的构造函数[因为它是全局变量]
2)内部构造函数afxCurrentWinApp对象将设置为当前对象(this)
3)在构造完所有全局变量后,WinMain将调用.
4)在WinMain中,它将调用CWinApp的InitInstance()[因为它是垂直函数]

注意:当我们调用AfxGetApp()时,我们将返回afxCurrentWinApp.
as Sauro Viti said CWinApp is not a singleton class.
while declaring a object of CWinApp class MFC stores first object to afxCurrentWinApp veriable.
Remember that MFC project has also WinMain(...) function.

We can see what will happen when we declare an object CWinApp theApp1;

1) It will call constructor of CWinApp [Because it is global variable]
2) Inside constructor afxCurrentWinApp object will set to current object ( this)
3) after all global variables construction WinMain will invoke.
4) inside WinMain it will call the CWinApp''s InitInstance() [ because it is vertual function]

Note: When we call AfxGetApp() we will return the afxCurrentWinApp.


这篇关于CWinApp如何实现单例模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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