Home | History | Annotate | Download | only in core
      1 /*
      2     Copyright 2010 Google Inc.
      3 
      4     Licensed under the Apache License, Version 2.0 (the "License");
      5     you may not use this file except in compliance with the License.
      6     You may obtain a copy of the License at
      7 
      8     http://www.apache.org/licenses/LICENSE-2.0
      9 
     10     Unless required by applicable law or agreed to in writing, software
     11     distributed under the License is distributed on an "AS IS" BASIS,
     12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13     See the License for the specific language governing permissions and
     14     limitations under the License.
     15  */
     16 
     17 #ifndef SkTRelay_DEFINED
     18 #define SkTRelay_DEFINED
     19 
     20 #include "SkRefCnt.h"
     21 
     22 /**
     23  *  Similar to a weakptr in java, a Relay allows for a back-ptr to an
     24  *  object to be "safe", without using a hard reference-count.
     25  *
     26  *  Typically, the target creates a Relay with a pointer to itself. Whenever it
     27  *  wants to have another object maintain a safe-ptr to it, it gives them a
     28  *  Relay, which they ref()/unref(). Through the Relay each external object can
     29  *  retrieve a pointer to the Target. However, when the Target goes away, it
     30  *  clears the Relay pointer to it (relay->set(NULL)) and then unref()s the
     31  *  Relay. The other objects still have a ref on the Relay, but now when they
     32  *  call get() the receive a NULL.
     33  */
     34 template <template T> class SkTRelay : public SkRefCnt {
     35 public:
     36     SkTRelay(T* ptr) : fPtr(ptr) {}
     37 
     38     // consumers call this
     39     T* get() const { return fPtr; }
     40 
     41     // producer calls this
     42     void set(T* ptr) { fPtr = ptr; }
     43 
     44     void clear() { this->set(NULL); }
     45 
     46 private:
     47     T* fPtr;
     48 };
     49 
     50 #endif
     51