Zerosquare (./57) :
topics/108059-trolloscope-who-is-the-best/72#2159 ?
merci, c'est exactement ça ^^
Zerosquare (./57) :
topics/108059-trolloscope-who-is-the-best/72#2159 ?
Texture *t = new Texture(); t->method(); delete t;
ref<Texture> t = newref Texture(); t->method();
void draw(Sprite *s) { ... } ref<Sprite> s = ...; draw(s); // Ou bien Sprite stackSprite; draw(&stackSprite);
Sprite *createSprite() { return new Sprite(...); } ref<Sprite> monSprite = mkref(createSprite());
void fonction(ref<Texture> tex) { ... } Texture t; fonction(&t);
ref<Texture> carTexture = newref FileTexture("voiture.png"); ref<Sprite> carSprite = newref Sprite(carTexture, 80, 35); // Egal à // ref<Sprite> carSprite = mkref(new Sprite(...));
struct __MkrefHelper { template<class T> ref<T> operator * (T *detachedRef) { return ref<T>(detachedRef, true); } }; #define newref __MkrefHelper() * new
template<class T>
class ref {
void incref() { if (counter) (*counter)++; }
void decref() { if (counter && --(*counter) == 0) delete ptr, delete counter; }
public:
T *ptr;
unsigned *counter;
ref() : ptr(0), counter(0) {}
ref(const ref<T> &ref) : ptr(ref.ptr), counter(ref.counter) { incref(); }
template<class U>
ref(const ref<U> &ref) : ptr(ref.ptr), counter(ref.counter) { incref(); }
ref(T *ptr) : ptr(ptr), counter(0) {}
ref(T *ptr, bool owned) : ptr(ptr) { counter = ptr ? new unsigned(1) : 0; }
// Nil-able
ref(int) : ptr(0), counter(0) {}
~ref() { decref(); }
template<class U>
ref<T> &operator = (const ref<U> &ref) {
// Using the same logic may free the original object if counter = 1
if (ref.ptr == ptr)
return *this;
// Else, do the equivalent of destructing "this" and constructing with "ref"
decref();
ptr = ref.ptr, counter = ref.counter;
incref();
return *this;
}
ref<T> &operator = (const ref<T> &ref) {
// Using the same logic may free the original object if counter = 1
if (ref.ptr == ptr)
return *this;
// Else, do the equivalent of destructing "this" and constructing with "ref"
decref();
ptr = ref.ptr, counter = ref.counter;
incref();
return *this;
}
ref<T> &operator = (T *newPtr) {
decref();
ptr = newPtr, counter = 0;
return *this;
}
void operator delete (void *) { throw "Must not delete refs!"; }
operator T* () const { return ptr; }
T* operator -> () const { return ptr; }
T& operator * () const { return *ptr; }
bool operator == (const ref<T> &ref) const { return ref.ptr == ptr; }
bool operator != (const ref<T> &ref) const { return ref.ptr != ptr; }
};
template<class T>
ref<T> mkref(T *obj) {
return ref<T>(obj, true);
}
struct __MkrefHelper {
template<class T>
ref<T> operator * (T *detachedRef) {
return ref<T>(detachedRef, true);
}
};
#define newref __MkrefHelper() * new