Objective-C @class / import best practice
I've noticed that a lot of Objective-C examples will forward declare classes with @class, then actually import the class in the .m file with an import. I understand that this is considered a best practice, as explained in answers to question: @class vs. #import
Coming from C++ this feels backwards. I would normally include all needed .h files in the new classes header file. This seems useful since it would make the compiler generate a warning when two classes include each ot开发者_StackOverflow中文版her, at which point I can decide whether this is a bad thing or not then use the same Objective-C style and forward declare the class in the header and include it in the .cpp file.
What is the benefit of forward declaring @class and importing in the implementation file? Should it be a best practice in C++ to forward declare classes rather than including the header file? Or is it wrong to think of Objective-C and C++ in these similar terms to begin with?
To be honest, your C++ is actually backwards. Generally in C++ you want to avoid headers being included inside other headers preferring forward declarations to includes. This is generally considered the best practice because it decreases compile time, and shrinks the size of the preprocessed code files fed into the compiler to as small as needed. Scott Meyers has a great section about that in Effective C++.
To more directly answer your question, the advantage of forward declaring classes, and importing them in the implementation file (in both C++ and objective c), is basically that forward declarations make it so that any other class using your class doesn't necessarily need to include all of the things your class uses. Which reduces the size of preprocessed code files (which makes preprocessing faster), makes compilation faster, and linking faster. All of which are usually good things. In more obscure cases having reduced include statements can make it easier to find certain types of errors (like missing semicolons in headers) that produce compiler warnings that aren't always obvious but are repeated and spammed everywhere headers are included.
精彩评论