Storage Allocation in Objective-C
Can this statement ever fail?
if (@"Hello") foo();
?
In other words can there be a situation where in the compiler fails to allocate enough storage space for literals. I know this 开发者_开发问答sounds ridiculous for short length literals but what about really long ones.
No.
NSString literals are "allocated" at compile time and form part of the text segment of your program.
Edit
To answer the other part of the question, if the compiler fails to allocate enough memory for the literal, the if statement won't fail, but the compilation will.
I don't know what the effective upper limit to the length of a string literal is, but it's bound to be less than NSIntegerMax
unichars
because NSNotFound
is defined as NSIntegerMax
. According to the clang docs, the length in bytes of a string literal is an unsigned int
and NSString string literals are sequences of unichars
.
I'm pretty sure if you try to compile a file with the literal
@" ... 1TB worth of characters ... "
the compiler will fail. The C standard available here says that any compatible compiler needs to support at least 4095 characters per string literal, etc. See Section 5.2.4.1. I'm sure GCC and clang allows much bigger literals.
精彩评论