Advertisement

smart pointer for reference counted objects

Started by July 04, 2010 09:35 AM
0 comments, last by WitchLord 14 years, 4 months ago
I wanted to implement some small smart pointer for angelscript, especially when passing handles from angelscript to c/c++ (so I can spare myself all the AddRef/Release calls). When I register a function that receives a handle, then it is passed by pointer:
void some_function(Foo* foo);


Adding a smart pointer means adding another line like this:
void some_function(Foo* foo){    smart_ptr<Foo> f(foo);    // only use 'f' from now on}


Though it would be easier if I could write my function like this:

void some_function(smart_ptr<Foo> foo);


I have little knowledge of assembler, but I know that pointer arguments are passed on the stack (under msvc and cdecl at least). Is the same true for small objects, like a smart_ptr would be?
I imagine an implementation like:
template <typename T>class as_pointer{public:    as_pointer(T* foo) : foo(foo) {}    as_pointer(as_pointer<T> that) : foo(that.foo) { if(foo) foo->AddRef(); }    ~as_pointer() { if(foo) foo->Release(); }private:    T* foo;}


It would have the same size as a pointer (given a padding of 4 bytes).
Do you think this can work under most compilers that angelscript already supports with native calling conventions?
Objects that have a constructor, destructor, and/or assignment operator are commonly passed by reference, regardless of the size of the objects.

Your suggestion will likely work for some compilers, but not for others. Only testing will let you determine which it work on, though I suspect it will work on MSVC but not on GNUC.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

This topic is closed to new replies.

Advertisement