Is implementing autorelease code in constructor a good idea ?

Nibbie
Posts: 4
Joined: 2009.10
Post: #1
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]
.
Quote this message in a reply
DoG
Moderator
Posts: 869
Joined: 2003.01
Post: #2
Don't do that. You can add a convenience function to the class, such as +[Foo fooWithBar:], but don't autorelease self in -init.
Quote this message in a reply
Member
Posts: 283
Joined: 2006.05
Post: #3
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.
Quote this message in a reply
Moderator
Posts: 1,560
Joined: 2003.10
Post: #4
Cocoa has well-defined conventions for this sort of thing.
Quote this message in a reply
⌘-R in Chief
Posts: 1,260
Joined: 2002.05
Post: #5
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.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Track down an autorelease bug kendric 2 3,397 Jun 28, 2009 05:09 AM
Last Post: kendric
  Autorelease pools Gillissie 16 6,339 Apr 22, 2009 02:43 PM
Last Post: kalimba