Autorelease

In C++


Point2D& Point2D::operator+(const Point2D & other)
{
     Point2D result(0.0f, 0.0f);
     result.v[0] = v[0] + other.v[0];
     result.v[1] = v[1] + other.v[1];
     return result;
} //ERROR – it results in a dangling reference because the local object is destructed prior to the return of the function



Point2D& Point2D::operator+(const Point2D & other)
{
     Point2D * result = new Point2D();
     result.v[0] = v[0] + other.v[0];
     result.v[1] = v[1] + other.v[1];
     return result;
} //ERROR – it results in memory leakage because nobody will delete the created object



Point2D Point2D::operator+ (const Point2D &other)
{
     Point2D result(0.0f, 0.0f);
     result.v[0] = v[0] + other.v[0];
     result.v[1] = v[1] + other.v[1];
     return result;
} // CORRECT – it returns a local class object by value
Point2D&
Point2D::operator+= (const Point2D &other)
{
     v[0] += other.v[0];
     v[1] += other.v[1];
     return *this;
} // CORRECT – it returns a self by reference




In Objective-C


-(Point2D*) add:(Point2D*)p1 and:(Point2D*)p2
{
     Point2D* result = [[Point2D alloc] initWithX:([p1 getX] + [p2 getX])
                                             andY:([p1 getY] + [p2 getY])];
     return result;
}
//ERROR : the function performs “alloc”, so, it is creating
//an object with a reference counter of 1. According
//to the rule, it should destroy the object.
//This can lead to a memory leak when summing three points :
[calculator add:[calculator add:p1 and:p2] and:p3];
//The result of the first addition is anonymous
//and nobody can release it. It is a memory leak.


-(Point2D*) add:(Point2D*)p1 and:(Point2D*)p2
{
     return [[Point2D alloc] initWithX:([p1 getX] + [p2 getX])
                                  andY:([p1 getY] + [p2 getY])];
}
//ERROR : This is exactly the same code as above. The fact that
//no intermediate variable is used does not change anything.


-(Point2D*) add:(Point2D*)p1 and:(Point2D*)p2
{
     Point2D* result = [[Point2D alloc] initWithX:([p1 getX] + [p2 getX])
                                             andY:([p1 getY] + [p2 getY])];
     [result release];
     return result;
}
//ERROR : obviously, it is nonsense to destroy the object after creating it



-(Point2D*) add:(Point2D*)p1 and:(Point2D*)p2
{
     Point2D* result = [[Point2D alloc] initWithX:([p1 getX] + [p2 getX])
                                             andY:([p1 getY] + [p2 getY])];
     [result autorelease];
     return result; //a shorter writing is “return [result autorelease]”
}
//CORRECT : “result” will be automatically released later,
//after being used in the calling code

Leave a Reply