延迟构造实例LazyInstance

延迟构造实例,简单来说就是一个类在没有用到的时候先占着一个坑,只有当真正用到的时候才开始倒入资源开始构造。最常见的就是我们平时用到的单例模式,实现的代码如下:

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值