为什么 NSString 不能取得分配给 new 的内存的所有权?

Why can NSString not take ownership of memory allocated with new?

Xcode 8(测试版 1)中的静态分析器警告我 NSStringinitWithBytesNoCopy:length:encoding:freeWhenDone: 无法获得 new[] 分配的内存的所有权。这是一个错误吗?如果不是,为什么会这样?

如果我将分配更改为使用 calloc 而不是 new[],警告就会消失。

关于 freeWhenDone 参数的文档是这样说的:

If YES, the receiver releases the memory with free() when it no longer needs the data; if NO it won’t.

所以 freeWhenDone 完成后直接调用 free()。要使用 new[],完成后必须 delete[]。因此,警告消息是正确的。如果您不想复制字节,则需要将 freeWhenDone 设置为 NO,并在不再需要时将字节设置为 delete[]