What is “the issue” with variable qualifier placement?

筅森魡賤 提交于 2019-12-21 17:23:40

问题


In this document, under the section labeled "Variable Qualifiers", Apple says:

You should decorate variables correctly. When using qualifiers in an object variable declaration, the correct format is:

ClassName * qualifier variableName;

for example:

MyClass * __weak myWeakReference;
MyClass * __unsafe_unretained myUnsafeReference;

Other variants are technically incorrect but are “forgiven” by the compiler. To understand the issue, see http://cdecl.org/.

Looking at cdecl.org doesn't clarify anything. Can anyone explain what "the issue" they are referring to is? In other words, help me convince others that this actually matters in a way that isn't just "because this one readme says so."


回答1:


See my examples with gibberish to English translations

It is well known that

ClassName * const varName; //varName is a constant pointer to ClassName

has different meaning than

const ClassName * varName; //varName is a pointer to constant ClassName

or

ClassName const * varName; //varName is a pointer to constant ClassName

In the same way this declaration

ClassName * __weak varName; //varName is a weak pointer to ClassName

and this declaration

__weak ClassName * varName; //varName is a pointer to weak?? ClassName??

are VERY different. However, the meaning of the second one is clear (although it's technically incorrect) and it can be "forgiven" by the compiler.

The correctness is a bit more important once you start working with pointers to pointers (e.g. Foo * __autoreleasing *).

I assume they wanted to protect beginner developers from the C/C++ declaration gibberish. Having the qualifier in the beginning seems more natural.



来源:https://stackoverflow.com/questions/23765950/what-is-the-issue-with-variable-qualifier-placement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!