Search code examples
shared-ptrobjective-c++

A std::tr1::shared_ptr for Objective C++ on iPhone?


I am mostly a C++ developer, recently I am writing iPhone applications.

The memory management on iPhone is OK to me, due to resource limitation, it's encouraged to use reference counters rather than deep copy.

One annoying thing is I have to manage the reference counters by myself: alloc means counter = 1; retain means counter++, release means counter--

I wish to write a shared_ptr like class for Cocoa Touch, so I rarely have to manually manipulate the reference counters by myself.

I doubt if there's any existing code for that, and I'd like to hear some advices, today is the 5th day since I started to learn objective c

Thanks.


Solution

  • As long as you learn the memory management rules first, there is no real problem with shared_ptr - it can help you in C++ contexts but doesn't let the ownership questions magically disappear.
    shared_ptr supports a custom deallocator so the following:

    @interface A : NSObject
    - (void)f;
    @end
    
    @implementation A
    - (void)dealloc { NSLog(@"bye"); [super dealloc]; }
    - (void)f { NSLog(@"moo"); }
    @end
    
    void my_dealloc(id p) {
        [p release];
    }
    
    // ...
    {
        shared_ptr<A> p([[A alloc] init], my_dealloc);
        [p.get() f];
    }
    

    ... outputs:

    moo
    bye

    ... as expected.

    If you want you can hide the deallocator from the user using a helper function, e.g.:

    template<class T> shared_ptr<T> make_objc_ptr(T* t) {
        return shared_ptr<T>(t, my_dealloc);
    }
    
    shared_ptr<A> p = make_objc_ptr<A>([[A alloc] init]);