iDevGames Forums
Is implementing autorelease code in constructor a good idea ? - Printable Version

+- iDevGames Forums (http://www.idevgames.com/forums)
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: iPhone, iPad & iPod Game Development (/forum-11.html)
+--- Thread: Is implementing autorelease code in constructor a good idea ? (/thread-682.html)



Is implementing autorelease code in constructor a good idea ? - Bracer - Oct 12, 2009 11:57 PM

Code:
-(id) init
{
    if (self = [super init])
    {
    [self autorelease];
    return self;
    }
}

With all the memory dangers that hides behind the corner and with the knowledge that there are functions that returns autorelease objects like arrayWithCapacity or stringWithFormat, shouldn't it be a good idea to also implement autorelease in our own objects like this code illustrated above for when the pool drains, it will go as well and there is no need to pollute the main codes with layers of
Code:
[object autorelease]
.


Is implementing autorelease code in constructor a good idea ? - DoG - Oct 13, 2009 12:25 AM

Don't do that. You can add a convenience function to the class, such as +[Foo fooWithBar:], but don't autorelease self in -init.


Is implementing autorelease code in constructor a good idea ? - maximile - Oct 13, 2009 06:17 AM

I can imagine it causing problems when you have subclasses releasing the same object. But it doesn't matter; even if there were no technical problems it'd still be a bad idea because it'd work differently to all the other Cocoa code out there.

You mention convenience methods (e.g. arrayWithCapacity); don't forget you can create those for your own classes. That's a great way to keep your main code free from memory management code.


Is implementing autorelease code in constructor a good idea ? - ThemsAllTook - Oct 13, 2009 06:50 AM

Cocoa has well-defined conventions for this sort of thing.


Is implementing autorelease code in constructor a good idea ? - SethWillits - Oct 13, 2009 12:41 PM

Bracer Wrote:... shouldn't it be a good idea to also implement autorelease in our own objects like this code illustrated above for when the pool drains, it will go as well and there is no need to pollute the main codes with layers of
Code:
[object autorelease]

So reasons above:
1) Consistency
2) Convenience methods already do this

But also:
3) Having everything autoreleased would mean the only way to explicitly deallocate an object when you want to (like in a tight loop) is to create and drain a surrounding pool. A simple alloc - release balance is cleaner and more efficient.

4) Post 4 from longjumper in this thread gives an architectural performance reason why this (specifically: autoreleasing every single object) would be a bad idea.


If you want to clean up your code then use the built-in garbage collection.