chromium之lazy_instance

先看看介绍
// The LazyInstance<Type, Traits> class manages a single instance of Type,
// which will be lazily created on the first time it's accessed.  This class is
// useful for places you would normally use a function-level static, but you
// need to have guaranteed thread-safety.  The Type constructor will only ever
// be called once, even if two threads are racing to create the object.  Get()
// and Pointer() will always return the same, completely initialized instance.
// When the instance is constructed it is registered with AtExitManager.  The
// destructor will be called on program exit.
//
// LazyInstance is completely thread safe, assuming that you create it safely.
// The class was designed to be POD initialized, so it shouldn't require a
// static constructor.  It really only makes sense to declare a LazyInstance as
// a global variable using the base::LinkerInitialized constructor.
//
// LazyInstance is similar to Singleton, except it does not have the singleton
// property.  You can have multiple LazyInstance's of the same type, and each
// will manage a unique instance.  It also preallocates the space for Type, as
// to avoid allocating the Type instance on the heap.  This may help with the
// performance of creating the instance, and reducing heap fragmentation.  This
// requires that Type be a complete type so we can determine the size.
//
// Example usage:
//   static LazyInstance<MyClass> my_instance(base::LINKER_INITIALIZED);
//   void SomeMethod() {
//     my_instance.Get().SomeMethod();  // MyClass::SomeMethod()
//
//     MyClass* ptr = my_instance.Pointer();
//     ptr->DoDoDo();  // MyClass::DoDoDo
//   }

1. 线程安全,构造成功后向AtExitManager注册,析构函数会在程序退出时调用

2. 类似Singleton,但是可以有多个同一个类型的LazyInstance,Singleton只能有一个类型的实例

3. POD https://akrzemi1.wordpress.com/2012/04/23/using-pods-in-c11/


 

 

引用了一个头文件

#include "base/dynamic_annotations.h"

参考分析chromium之dynamic_annotations,使用valgrind等动态分析工具,会影响最终生成的代码

 

下一个头文件

#include "base/at_exit.h"

参考分析chromium之at_exit,调用回调及单例的析构函数

 


posted on 2018-06-09 10:21  ckelsel  阅读(329)  评论(0编辑  收藏  举报

导航