Home | History | Annotate | Download | only in memory
      1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "base/memory/weak_ptr.h"
      6 
      7 namespace base {
      8 namespace internal {
      9 
     10 WeakReference::Flag::Flag() : is_valid_(true) {
     11   // Flags only become bound when checked for validity, or invalidated,
     12   // so that we can check that later validity/invalidation operations on
     13   // the same Flag take place on the same sequenced thread.
     14   sequence_checker_.DetachFromSequence();
     15 }
     16 
     17 void WeakReference::Flag::Invalidate() {
     18   // The flag being invalidated with a single ref implies that there are no
     19   // weak pointers in existence. Allow deletion on other thread in this case.
     20   DCHECK(sequence_checker_.CalledOnValidSequence() || HasOneRef())
     21       << "WeakPtrs must be invalidated on the same sequenced thread.";
     22   is_valid_ = false;
     23 }
     24 
     25 bool WeakReference::Flag::IsValid() const {
     26   DCHECK(sequence_checker_.CalledOnValidSequence())
     27       << "WeakPtrs must be checked on the same sequenced thread.";
     28   return is_valid_;
     29 }
     30 
     31 WeakReference::Flag::~Flag() {
     32 }
     33 
     34 WeakReference::WeakReference() {
     35 }
     36 
     37 WeakReference::WeakReference(const Flag* flag) : flag_(flag) {
     38 }
     39 
     40 WeakReference::~WeakReference() {
     41 }
     42 
     43 WeakReference::WeakReference(WeakReference&& other) = default;
     44 
     45 WeakReference::WeakReference(const WeakReference& other) = default;
     46 
     47 bool WeakReference::is_valid() const { return flag_.get() && flag_->IsValid(); }
     48 
     49 WeakReferenceOwner::WeakReferenceOwner() {
     50 }
     51 
     52 WeakReferenceOwner::~WeakReferenceOwner() {
     53   Invalidate();
     54 }
     55 
     56 WeakReference WeakReferenceOwner::GetRef() const {
     57   // If we hold the last reference to the Flag then create a new one.
     58   if (!HasRefs())
     59     flag_ = new WeakReference::Flag();
     60 
     61   return WeakReference(flag_.get());
     62 }
     63 
     64 void WeakReferenceOwner::Invalidate() {
     65   if (flag_.get()) {
     66     flag_->Invalidate();
     67     flag_ = NULL;
     68   }
     69 }
     70 
     71 WeakPtrBase::WeakPtrBase() {
     72 }
     73 
     74 WeakPtrBase::~WeakPtrBase() {
     75 }
     76 
     77 WeakPtrBase::WeakPtrBase(const WeakReference& ref) : ref_(ref) {
     78 }
     79 
     80 }  // namespace internal
     81 }  // namespace base
     82