2

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?

4

2 回答 2

7

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.

于 2010-09-17T01:57:45.103 回答
0

该函数可以返回 aCGPoint因为结构“足够小”可以直接从函数返回。您没有返回指针,而是直接返回整个内容。与CGPoints作为参数的方法相同——您可以直接按值传递整个事物。

正如 Dave 所说,CGPoints 不是对象,它们只是结构。CGPointMake不“分配”内存。它只是一个返回具有正确大小设置的结构的函数,然后您通常会将其捕获到您自己的堆栈上的本地或传递或其他任何东西。

与任何其他原始类型(int、float 或其他结构)一样,它在超出范围时不需要被释放。

(注意:许多架构/编译器/“应用程序二进制接口”对用作参数或返回值的事物的大小进行了优化和大小限制。在这种情况下,CGPoint 实际上可以完全适合一个 64 位寄存器( 2x 32 位浮点数),这使得它不比返回一个 int 更重量级。但编译器也可以做其他技巧,比如复制进出更大的结构,例如 CGRect。)

于 2010-09-17T02:04:26.880 回答