views:

51

answers:

2

refer to http://stackoverflow.com/questions/1746378/cgpointmake-explaination-needed

Correct me if I am wrong, in the implementation of CGPointMake, CGPoint p; declare a local variable of a struct, which should should be freed after leaving the scope. But why the function can return the value without risk?

Anyway, assume that implementation of CGPointMake is correct, should I free the CGPoint that created by CGPointMake?

+4  A: 

It doesn't need to be freed, because it never lived on the heap. Only heap-allocated memory needs to be freed. Memory that is allocated on the stack (as is done in CGPointMake()) will be cleaned up automatically after the method/function exists.

The function can return a point because the compiler sees "Aha, this function wants to return a struct, which is sizeof(CGPoint) bytes big, so I'll make sure that there's enough space in the return value memory slot for something that big." Then as the function exits, the return value is copied in to the return memory slot, the function exits, and the value in the return slot is copied over to its new destination.

Dave DeLong
And in keeping with Apple's naming convention, we know that we don't need to free it because it doesn't have the word "Create" or "Copy" in the function name (following the Create Rule). Apple typically uses Make in situations where the thing being returned is a struct, but the more important point is learning the Create Rule and the equivalent Cocoa memory management rule (new, alloc, copy).
Rob Napier
oh ya and i suddenly realize the problem by considering struct variable as int variable :D
Kay Chan
and thx for Rob Napier's suppliment
Kay Chan
A: 

The function can return a CGPoint because the struct is "small enough" to be returned directly from a function. You're not returning a pointer, you're returning the whole thing directly. Same with methods that take CGPoints as parameters-- you can pass the whole thing by value directly.

As Dave notes, CGPoints aren't objects, they're just structs. CGPointMake doesn't "allocate" memory. It's just a function that returns a struct set up with the right sizes, which you then usually capture into a local on your own stack or pass along or whatever.

Like any other primitive type (int, float, or other struct), it doesn't need to be freed when it goes out of scope.

(Note: many architectures/compilers/"application binary interface"s have optimizations and size limits regarding the size of a thing used as an argument or return value. In this case, a CGPoint could actually fit entirely inside one 64-bit register (2x 32-bit floats) which makes it no more heavyweight than returning an int. But the compiler can also do other tricks as far as copying in and out larger structures e.g. CGRect.)

quixoto
thx for ur ans but i think Dave DeLong's one is better
Kay Chan