iOS 关联对象 - DisguisedPtr

// DisguisedPtr acts like pointer type T*, except the 
作用类似指针类型T*,
// stored value is disguised to hide it from tools like `leaks`.
只是将存储值隐藏起来,不让“ leaks”之类的工具看到。 leaks内存泄漏检测工具
// nil is disguised as itself so zero-filled memory works as expected, 
nil被伪装成它自己,所以填满0的内存就像预期的那样工作
// which means 0x80..00 is also disguised as itself but we don't care.
这意味着0 x80 . .00也伪装成它自己,但我们不在乎。
// Note that weak_entry_t knows about this encoding.
注意weak_entry_t知道这种编码。
template 
class DisguisedPtr {
    uintptr_t value;

    static uintptr_t disguise(T* ptr) {
        return -(uintptr_t)ptr;
    }

    static T* undisguise(uintptr_t val) {
        return (T*)-val;
    }

 public:
    DisguisedPtr() { }
    DisguisedPtr(T* ptr) 
        : value(disguise(ptr)) { }
    DisguisedPtr(const DisguisedPtr& ptr) 
        : value(ptr.value) { }

    DisguisedPtr& operator = (T* rhs) {
        value = disguise(rhs);
        return *this;
    }
    DisguisedPtr& operator = (const DisguisedPtr& rhs) {
        value = rhs.value;
        return *this;
    }

    operator T* () const {
        return undisguise(value);
    }
    T* operator -> () const { 
        return undisguise(value);
    }
    T& operator * () const { 
        return *undisguise(value);
    }
    T& operator [] (size_t i) const {
        return undisguise(value)[i];
    }

    // pointer arithmetic operators omitted 
    // because we don't currently use them anywhere
};

你可能感兴趣的:(iOS 关联对象 - DisguisedPtr)