Skip to content

Instantly share code, notes, and snippets.

@melpon
Last active December 31, 2015 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melpon/7983935 to your computer and use it in GitHub Desktop.
Save melpon/7983935 to your computer and use it in GitHub Desktop.
cocos2d 用 intrusive_ptr。適当に書いたので間違ってるところあるかも。
#ifndef CC_PTR_INCLUDED
#define CC_PTR_INCLUDED
/*
static void intrusive_ptr_add_ref(cocos2d::CCObject* p) {
p->retain();
}
static void intrusive_ptr_release(cocos2d::CCObject* p) {
p->release();
}
#include "intrusive_ptr.hpp"
// to short name
template<class T>
using cc_ptr = intrusive_ptr<T>;
*/
#include <utility>
template<class T>
class cc_ptr {
public:
cc_ptr() : p(nullptr) { }
explicit cc_ptr(T* p, bool add = true) : p(p) {
if (p && add) p->retain();
}
cc_ptr(const cc_ptr& rhs) : p(rhs.p) {
if (p) p->retain();
}
template<class U>
cc_ptr(const cc_ptr<U>& rhs) : p(rhs.get()) {
if (p) p->retain();
}
cc_ptr(cc_ptr&& rhs) : p(rhs.p) {
rhs.p = nullptr;
}
template<class U>
cc_ptr(cc_ptr<U>&& rhs) : p(rhs.p) {
rhs.p = nullptr;
}
~cc_ptr() {
if (p) p->release();
}
void swap(cc_ptr& rhs) {
std::swap(p, rhs.p);
}
cc_ptr& operator=(const cc_ptr& rhs) {
cc_ptr(rhs).swap(*this);
return *this;
}
template<class U>
cc_ptr& operator=(const cc_ptr<U>& rhs) {
cc_ptr(rhs).swap(*this);
return *this;
}
cc_ptr& operator=(cc_ptr&& rhs) {
cc_ptr(std::move(rhs)).swap(*this);
return *this;
}
template<class U>
cc_ptr& operator=(cc_ptr<U>&& rhs) {
cc_ptr(std::move(rhs)).swap(*this);
return *this;
}
void reset(T* p = nullptr, bool add = true) {
cc_ptr(p, add).swap(*this);
}
T* get() const{ return p; }
T& operator*() const{ return *p; }
T* operator->() const{ return p; }
explicit operator bool() const{ return p; }
bool operator!() const{ return !p; }
private:
T* p;
};
template<class T>
bool operator==(const cc_ptr<T>& lhs, const cc_ptr<T>& rhs) {
return lhs.get() == rhs.get();
}
template<class T>
bool operator!=(const cc_ptr<T>& lhs, const cc_ptr<T>& rhs) {
return !(lhs == rhs);
}
template<class T>
bool operator< (const cc_ptr<T>& lhs, const cc_ptr<T>& rhs) {
return lhs.get() < rhs.get();
}
template<class T>
bool operator> (const cc_ptr<T>& lhs, const cc_ptr<T>& rhs) {
return rhs < lhs;
}
template<class T>
bool operator<=(const cc_ptr<T>& lhs, const cc_ptr<T>& rhs) {
return !(rhs < lhs);
}
template<class T>
bool operator>=(const cc_ptr<T>& lhs, const cc_ptr<T>& rhs) {
return !(lhs < rhs);
}
#endif // CC_PTR_INCLUDED
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment