Home | History | Annotate | Download | only in core
      1 
      2 /*
      3  * Copyright 2010 Google Inc.
      4  *
      5  * Use of this source code is governed by a BSD-style license that can be
      6  * found in the LICENSE file.
      7  */
      8 
      9 
     10 #ifndef SkTRelay_DEFINED
     11 #define SkTRelay_DEFINED
     12 
     13 #include "SkRefCnt.h"
     14 
     15 /**
     16  *  Similar to a weakptr in java, a Relay allows for a back-ptr to an
     17  *  object to be "safe", without using a hard reference-count.
     18  *
     19  *  Typically, the target creates a Relay with a pointer to itself. Whenever it
     20  *  wants to have another object maintain a safe-ptr to it, it gives them a
     21  *  Relay, which they ref()/unref(). Through the Relay each external object can
     22  *  retrieve a pointer to the Target. However, when the Target goes away, it
     23  *  clears the Relay pointer to it (relay->set(NULL)) and then unref()s the
     24  *  Relay. The other objects still have a ref on the Relay, but now when they
     25  *  call get() the receive a NULL.
     26  */
     27 template <template T> class SkTRelay : public SkRefCnt {
     28 public:
     29     SkTRelay(T* ptr) : fPtr(ptr) {}
     30 
     31     // consumers call this
     32     T* get() const { return fPtr; }
     33 
     34     // producer calls this
     35     void set(T* ptr) { fPtr = ptr; }
     36 
     37     void clear() { this->set(NULL); }
     38 
     39 private:
     40     T* fPtr;
     41 };
     42 
     43 #endif
     44