Transferred from: http://roclinux.cn/?p=3285
This original article belongs to the "Linux Greenhouse" blog.
The blog address is http://roclinux.cn.
The author of the article is Roc Wu
==
Specification
For normal classes, it is recommended to use a predecessor declaration instead of # include.
"What is a predecessor statement"
In English, a predecessor declaration, called "forward declaration", refers to "declaring a class, function, or template without related specific definitions". We can use the predecessor declaration instead of the # include statement for the declaration.
"Voice of the Supporters"
Too many # include causes the compiler to open many files and process a lot of input. In addition, when the head file content is modified, it also causes more recompilation.
If we use the predecessor declaration, we can avoid the above problem.
"The voice of the opponents."
- In the use of templates, typedef, default parameters and other syntax, we are more difficult to determine the correct form of the predecessor Declaration;
- For a piece of code, it is difficult to decide whether to use a pre-declaration or an # include, especially if there is an implicit conversion operation. In some extreme cases, replacing # include with a predecessor declaration completely alters the original intent of the code.
- If you want to pre-declare too much content, it will appear redundant procrastination, as easy as # include.
- The pre-declaration of functions and templates prevents the original author from improving the function or template, such as adjusting the type of a parameter, adding a default value to the parameters of the template, and so on.
- The namespace std:: The pre-declaration of the tag, often produces an "undefined" error.
- If you deliberately tweak your code to use a predecessor declaration, you tend to slow down your code and complicate the logic of your code, such as using pointer members instead of object members.
- The benefits of the pre-statement to code efficiency are not being proven.
Conclusion
- If you want to use a function in the header file, use the # include method to reference the header file
- If you want to use a class template from a header file, use the # include method to reference the header file
- If you want to use a generic class, it is recommended that you use a predecessor declaration.
- You do not need to substitute pointer members for object members just to avoid using # include.
Thank you!
Google C + + Programming specification – 19th – "Pre-declaration"