extern vs Singleton班 [英] extern vs Singleton class

查看:69
本文介绍了extern vs Singleton班的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们使用extern关键字有一些外部链接.

Say we have some external linkage using the extern keyword.

我有(在class1.cpp中):

I have (in class1.cpp):

MyClass* myClassVar = NULL;

构造函数将初始化以上内容,然后析构函数将其删除.

The constructor initializes the above, and destructor deletes.

然后在class2.cpp和class3.cpp中有:

Then in class2.cpp and class3.cpp there is:

extern MyClass* myClassVar;

这些类使用myClassVar(进行常规的null检查等).

These classes use myClassVar (doing the usual null checks etc).

将首选Singleton吗?(我知道全局变量不好,而Singleton只是语法糖).将上面的代码更改为下面的代码是否有好处?

Would a Singleton be preferred? (I know globals are bad etc, and a Singleton is just syntax sugar). Is there an advantage to change the above code to the below?

static Singleton& getInstance()
{
   static Singleton instance;

   return instance;
}

然后所有类都将做:

Singleton::getInstance()

推荐答案

全局变量受初始化顺序惨败的困扰.单独翻译单元中的全局变量以未指定的顺序初始化,因此,如果在其构造函数中引用另一个时,您将获得不确定的行为.

Global variables suffer from the initialisation order fiasco. Globals in separate translation units are initialised in an unspecified order, so you get undefined behaviour if one refers to another in its constructor.

函数范围内的静态变量在第一次调用该函数时进行初始化,(或多或少)解决了初始化顺序问题.

Static variables in a function scope are initialised the first time the function is called, which (more or less) solves the initialisation order problem.

但是,仍然存在更多的细微问题.特别是,在对象被销毁后仍然可以访问它,并且还有一些开销来确保线程安全的初始化(并且,在较早的编译器中,初始化可能根本不是线程安全的).没有一种完全安全的方法来管理非平凡类型的全局可访问对象,我的建议是尽可能避免使用它们.

However, more subtle problems remain; in particular, it is still possible to access the object after it has been destroyed, and there is some overhead to ensure thread-safe initialisation (and, in older compilers, initialisation might not be thread-safe at all). There is no completely safe way to manage globally accessible objects of non-trivial types, and my advice would be to avoid them altogether if possible.

这篇关于extern vs Singleton班的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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