1,栈上分配内存
private: int8_t buf_[sizeof(_Ty)]; _Ty *instance_; DISALLOW_COPY_AND_ASSIGN(LazyInstance); };
2. 惰性初始化,在真正用到时才调用构造函数
_Ty* getPtr() { if (!Traits::kAllowedToAccessOnNonjoinableThread) ThreadRestrictions::assertSingletonAllowed(); if ((NoBarrier_Load(&state_) != STATE_CREATED) && needsInstance()) { instance_ = Traits::New(buf_); completeInstance(instance_, Traits::Delete); } return instance_; }
3. 线程安全
bool LazyInstanceHelper::needsInstance() { if (Acquire_CompareAndSwap(&state_, STATE_EMPTY, STATE_CREATING) == STATE_EMPTY) { return true; } else { while (NoBarrier_Load(&state_) != STATE_CREATED) { ThreadData::yieldCurrentThread(); } } return false; }
4. 用法
static LazyInstance<MyClass> my_instance(base::LINKER_INITIALIZED); void SomeMethod() { my_instance.Get().SomeMethod(); MyClass::SomeMethod() MyClass* ptr = my_instance.Pointer(); ptr->DoDoDo(); }