延迟构造实例,简单来说就是一个类在没有用到的时候先占着一个坑,只有当真正用到的时候才开始倒入资源开始构造。最常见的就是我们平时用到的单例模式,实现的代码如下:
template<typename Type>
class CSingleton {
private:
CSingleton() {}
static Type *m_pInstance;
public:
static Type * GetInstance() {
if(m_pInstance == NULL)
m_pInstance = new Type();
return m_pInstance;
}
};
template<typename Type>
Type * CSingleton<Type>::m_pInstance = NULL;
这个类的只有在调用GetInstance才对 m_pInstance进行初始化,就体现了用到才实例化的思想。这样做的好处是加速程序的启动过程,比如一个界面的菜单对象,当你还没有点击菜单之前就创造了,那他一定会影响软件的启动性能。在chromium中,实现延迟构造的是一个LazyInstance类,这个类比起上边这个类复杂很多,我起初也觉得上边的单例也很足够了,在深入了解LazyInstance类后,我却感觉我的见识还是太少了。
lazy_instance.h
template <typename Type>
struct DefaultLazyInstanceTraits {
static const bool kRegisterOnExit = true;
static Type* New(void* instance) {
DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (ALIGNOF(Type) - 1), 0u)
<< "error message";
return new (instance) Type();
}
static void Delete(Type* instance) {
instance->~Type();
}
};
namespace internal {
template <typename Type>
struct LeakyLazyInstanceTraits {
static const bool kRegisterOnExit = false;
static Type* New(void* instance) {
return DefaultLazyInstance