문제

refer to 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?

도움이 되었습니까?

해결책

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.

다른 팁

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.)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top