为什么必须释放这些数据?我是主人吗? [英] Why must I free this data? Am I the owner?

查看:57
本文介绍了为什么必须释放这些数据?我是主人吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很奇怪.在技术问答中, A ,苹果这样说:

This is strange. In a technical Q & A, Apple says this:

void *data = CGBitmapContextGetData (cgctx);
if (data != NULL)
{

    // **** You have a pointer to the image data ****

    // **** Do stuff with the data here ****

}

// When finished, release the context
CGContextRelease(cgctx); 
// Free image data memory for the context
if (data)
{
    free(data);
}

我查找了CGBitmapContextGetData的文档,并且没有提到我在调用此数据时负责发布数据.已经有CGContextRelease调用可以清理上下文.

I looked up the documentation for CGBitmapContextGetData, and it does not mention that I am responsible for releasing the data when I call this. There is already the CGContextRelease call which cleans up the context.

必须在上下文中额外释放数据的意义是什么?它只是指向该数据的指针,对吗?他们为什么在这里叫free(data)?

What is the point of having to extra-release the data inside the context? It is just a pointer to that data, right? Why do they call free(data) here?

推荐答案

更新:我忽略了阅读完整的代码示例. Apple在CreateARGBBitmapContext()中分配了bitmapData,但没有释放它.这是完全可以的,因为上下文仍然需要引入上下文中.

Update: I neglected to read the entire code example. Apple allocates bitmapData in CreateARGBBitmapContext() but does not free it. Which is perfectly fine, since the context still needs to do draw into it.

但是,bitmapData将在处理完图形后稍后被释放,这恰好是它们在ManipulateImagePixelData()末尾所做的.因此,尽管释放通过get函数获得的内容并不常见,但它示例代码是正确的.

However, bitmapData will have to later be released when they're done with the drawing, which is exactly what they do at the end of ManipulateImagePixelData(). So while it is unusual to release something that was obtained by a get function, it the sample code is correct.

为避免混淆从get函数返回的内容,可能需要将位图数据存储在全局/实例变量中,并在完成后将其保存在free()中.

To avoid the confusion of freeing something that was returned from a get function, one might want to store the bitmap data in a global / instance variable and free() that when done.

我认为这是代码示例中的错误. 该功能的文档中没有提及任何特殊内容,因此没有理由为什么 Quartz 2D文档还特别重申了CoreFoundation内存管理模型适用于Quartz 2D API.

I would assume this to be a bug in the code example. The documentation of this function does not mention anything special, so there's no reason why the Get Rule would not apply here. The Quartz 2D Documentation also specifically reiterates that the CoreFoundation memory management model applies to the Quartz 2D API.

这篇关于为什么必须释放这些数据?我是主人吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆