Give you a clear understanding of C + +

Source: Internet
Author: User

31 years ago (1979), a researcher who had just received a doctorate, developed a new programming language for a software project called Bjarne Stroustrup, which was named--c with classes and renamed C + + after four years. C + + is a universal programming language that supports a variety of programming paradigms, including procedural, object-oriented (object-oriented programming, OP), generics (generic programming, GP), and later templates designed for generics, is found and proved to be Turing-complete, so C + + can also support the template meta-programming paradigm (template metaprogramming, TMP). C + + inherits the special features of C. Both high-level and low-level language functions, which can be used as both system and application programming languages. Three Kingdoms Live Casino

C + + is widely used in different fields, with millions of users. According to the survey of the past ten years, the prevalence of C + + is about stable 3rd (after C/java). C + + has experienced long-term practice and evolution before it becomes today's appearance. In 1998, the C + + Standards Committee had overcome all odds to make C + + an ISO standard (commonly known as c++98) with a very powerful standard template library, STL. The Committee then submitted its first technical report on the standard library (TR1) in 2005 and worked for the next standard c++0x. Unfortunately c++0x can not be completed in 200x years, all sectors hope that the new standard can be introduced in 2011.

In the popular C + + compiler, Microsoft Visual C + + 2010 has implemented part of the C++0X syntax and joined the TR1 expansion library, while GCC supports c++0x syntax and libraries more than VC2010.

Should I choose c + +

1. What are the appropriate procedures for using C + +?

C + + is not a panacea, I cite some of the experience of C + + application time.

    • C + + is suitable for the construction program of the more stable parts of the requirements of the larger parts can use scripting language;
    • The program must maximize the performance of the hardware, and the performance bottleneck is CPU and memory;
    • The program must communicate with the operating system or hardware frequently;
    • The program must use C + + frameworks/libraries, such as most game engines (such as Unreal/source) and middleware (such as Havok/fmod), although some C + + libraries provide bindings in other languages, but usually native API performance is best and up-to-date;
    • A target platform in the project provides support for the C + + compiler only.

By application domain, C + + is suitable for development server software, desktop applications, games, real-time systems, high-performance computing, embedded systems and so on.

2. Use C + + or C?

The design philosophy of C + + and C is different, so different programmers and software projects have different choices and are difficult to generalize. Compared with C + +, C has the advantages of fast compilation, easy learning, explicit description of program details, less update criteria (both of which can be considered as drawbacks). At the language level, C + + contains most of the functions of the C language (one exception, C + + has no C99 variable-length array VLA), and provides the features of OOP and GP. But in fact, using C can also realize the OOP idea, can also use the macro to achieve a certain degree of GP, but the C + + syntax can be more concise, automatic implementation of OOP/GP. C + + 's RAII (resource acquisition is initialization, resource acquisition is initialization) features are unique and C/c#/java has no corresponding function. Looking back on history, Stroustrup developed the early C + + compiler Cpre/cfront to translate C + + source code into C, and then compile it with the C compiler. It can be concluded that C + + programs written by the equivalent C program, but C + + at the language level provides OOP/GP syntax, stricter type checking system, a large number of additional language features (such as exceptions, RTTI, etc.), and the C + + standard library is also rich. Sometimes the syntax of C + + can make programs more concise, such as operator overloading, implicit conversions. On the other hand, the C language API is generally simpler than C + + and can be easily invoked by other language programs. As a result, some C + + libraries provide a C API encapsulation and are also available for C program invocation. Conversely, C's API is sometimes encapsulated in C + + to support RAII and other C + + library integrations.

3. Why is C + + performance better than other languages?

Relative to the Virtual machine language (for example, C#/java), C + + directly compiles the source program into the machine code of the target platform in a static form. In general, C + + programs can be compiled and linked with the most optimized optimizations, the fastest startup, and the least extra memory overhead at runtime. The relative dynamic language (such as Python/lua) of C + + also reduces the dynamic type detection at runtime. In addition, C + + operations are deterministic, with no additional behavior (for example, C#/java is bound to initialize variables), and no delay in the uncertainty caused by garbage collection (GC), and the layout of the data structure in C + + in memory is also deterministic. Sometimes some features of C + + will make program performance better than C, which is the most prominent in the inline and the template, these two features make the C + + standard library's sort () is usually more than the C standard library qsort () more than a few times (c available macros or manual coding to solve the problem). On the other hand, C + + can directly map machine code, there is no other intermediate language, so you can do the underlying optimization, such as the use of internal (intrinsic) functions and embedded assembly language. However, many of the performance benefits of C + + are not free lunches, including longer compile link times and more error-prone, thus increasing development time and cost, which is later supplemented.

C + + FAQs

1. C + + source code cross-platform?

C + + has good cross-platform capabilities, but due to direct mapping of hardware, performance-optimized relationships, cross-platform capabilities are less than Java and most scripting languages. However, it is still possible to practice cross-platform C + + software, but be aware of the following issues:

    • The C + + standard does not specify the size of the original data type (such as int), when a particular size is required, the type can be customized (such as int32_t), and sizeof () is used for any type without assuming its size;
    • byte order (byte order) varies by CPU, with particular attention to binary input and output, reinterpret_cast method;
    • There are differences in the address alignment between the original data and the structure type;
    • Some compiler or platform-specific extensions are provided by the compiler;
    • Avoid the assumption that the binary interface (application binary interface, ABI) is applied, for example, when calling a function, the order of the parameters is not defined in C + +, and in C + + it is not possible to assume rtti/virtual table.

In summary, cross-platform C + + software can use macros to detect the compiler and platform in the header file, and then use macros, typedef, custom platform-related implementations and other methods to practice cross-platform, the C + + standard does not provide this kind of help.

2. C + + program easy to crash?

In contrast to many languages, C + + provides unsafe functionality to optimize performance and possibly cause crashes. Note, however, that many run-time errors, such as referencing to null pointers/references, arrays out of bounds, stack overflows, and so on, are error-free or throw exceptions in other languages, which are procedural problems, not language itself. Some argue that this type of run-time error should be written to the log and crash immediately, and should not allow the program to continue to run in order to avoid a greater impact (for example, the program continues to overwrite the file with the wrong data in memory). To be fault tolerant, you can split the program into multiple processes, like chrome or using fork () as a business. However, C + + has many mechanisms to reduce errors, such as String instead of C string, vector or array (TR1) instead of the original array (some implementations can detect out-of-bounds in debug mode), and smart pointers can reduce some of the original pointers. In addition, the bug I encountered most often was that there was no initialization of member variables, which sometimes caused crashes, and the behavior of the debug and release versions might be different.

3. C + + To do memory management manually?

C + + also provides automatic local variables on the stack, as well as objects allocated from free store. For the latter, programmers need to release manually, or use different containers and smart pointers. C + + programmers often further optimize memory and customize memory allocation policies to improve performance, such as using object pooling, custom one-way/bidirectional stacking areas, and so on. Although c++0x has not yet added GC functionality, it is also possible to write or use off-the-shelf libraries yourself. In addition, C + + can directly use the memory-related features provided by the operating system, such as memory-mapped files, shared memory, and so on.

4. Do I use C + + to re-create wheels?

The C + + projects I have worked with have re-created many of the features that the standard library has already provided, which is rare in other languages. I'm trying to analyze why. First, the C + + standard library is poor in comparison to many languages, and developers are repeatedly making custom libraries. From another point of view, the C + + standard library is written in C + + (many other languages do not use themselves instead of writing libraries in C + +), in terms of capabilities and performance, the custom library and standard library are not essential differences, in addition, the standard library for the general purpose, the different platforms and the use of a variety of demand, performance, For example, the EA Company has published self-made EASTL specifications, describing the performance and functional requirements of the game development of the STL features; In addition, multiple C + + libraries are used together, often due to conflicting specifications, or overlapping functions, so projects may have to be developed on their own, or introduced into the concept or implementation of other libraries ( such as Boost/tr1/loki), rewritten to conform to the project specification.

5. C + + compilation speed is slow?

Wrong, is very slow. I think C + + might be the slowest compiler in a utility language. This problem involves the way C + + inherits the compilation link, and adds a complex class/generic declaration and inline mechanism to multiply the compilation time. In C + + before the compilation method reform (such as the module proposal), you can use the following techniques to improve: first, the use of Pimpl method, because of the performance of the loss of the application of the number of classes; second, only the necessary header files, and try to use and provide the predecessor declaration version of the header file (such as IOSFWD) Thirdly, we adopt interface-based design, but we should pay attention to the cost of virtual function call; Finally, the unity build is used to compile multiple CPP files in a compilation unit, and a distributed generation system such as IncrediBuild is adopted.

6. What features does C + + lack?

Although C + + is already very complex, there are still many common features missing. C++0X has made a number of improvements, such as adding lambda functions, closures, type deduction declarations, and so on, while library aspects include regular expressions, unordered_set/unordered_map with hash tables, reference counting smart pointers shared_ptr/ Weak_ptr and so on. But the most notable thing is that c++0x introduces multithreading syntax and library functionality, which is a big step in C + + evolution. However, the modules, GC, reflection mechanism and other functions, although the proposal, but did not add c++0x.

Recommendations for using C + +

1. Select the feature set for the application

I agree with Stroustrup's response to the various technologies used in C + +: "What you can do doesn't mean you have to do it." (Just because you can do it, doesn ' t mean so you had to.) " C + + is rich in features, but it also brings different problems, such as excessive complexity, compilation, and loss of running performance. It is generally possible to consider the use of multiple inheritance, exceptions, RTTI, and the extent to which the use of templates and template meta-programming can be adjusted. Using overly complex designs and features can make it harder for some team members to understand and maintain.

2. Establish programming specifications for the team

C + + has a high degree of freedom of coding, easy to write different styles of code, C + + itself does not define some standard specifications. Moreover, the source file of C + + is physically constituted, which is more complex than many languages. Therefore, in addition to determining the feature set, each team should establish a set of programming specifications, including the source file format (which can be used with the file template), and the curly brace style.

3. Try to use C + + style rather than C style

Because C + + has a C-compatible burden, some features can be implemented using C-style, but it is best to use the new features provided by C + +. The most basic is to try to use named constants, inline functions and generics to replace macros, only the macros used in conditional compilation and special cases. Legacy C requires local variable declarations at the beginning of the scope, C + + does not have this limitation, the variable declaration should be placed as close as possible to where it is used, and for () the loop variable declaration can be placed in the parentheses. The ability to enforce type safety in C + + should be used as much as possible, such as avoiding the "universal" pointer void *, using an individual or generic type, representing a Boolean value with a bool rather than an int, and choosing 4 C + + cast keywords instead of a simple cast.

4. Combine other languages

As mentioned earlier, C + + is not suitable for all application scenarios and can sometimes be mixed with other languages, including extending other languages in C + + or embedding scripting language engines in C + + programs. For the latter, you can use boost or swig for consolidation, in addition to specialized APIs that use a variety of scripting languages.

C + + Learning recommendations

One of the drawbacks of C + + is that it is relatively complex in many languages and difficult to learn. Many people say that learning C only requires a K&R C programming language, but C + + books are numerous. I went from c to C + +, all by reading self-study. Share a little learning experience here. Personally, learning C + + can be divided into 4 levels:

    • The first level, C + + Fundamentals: Pick a Primer book, such as "C + + Primer", "C + + University Tutorial", or Stroustrup wrote the classic "C + + programming language" or his 1.5 new book "C + + programming principles and practice," and the general C + + course also ends here, in addition to the C + + Standards library and the C + + standard library Extensions can be used for reference;
    • The second level, the correct and efficient use of C + +: This level must start self-study, read the "(more) effective C + +", "(more) exceptional C + +", "effective STL" and "C + + programming Code", etc., it is appropriate to step into the professional C + + The road of development;
    • Third level, in-depth understanding of C + +: About the global problem readable "in-depth exploration of C + + object Model", "imperfect C + +", "C + + meditation", "STL Source Analysis", to challenge IQ, can see the template and template meta-programming books such as "C + + Templates", "C + + Design new thinking "," C + + template meta-programming ";
    • Level four, study C + +: Read the design and evolution of C + +, the nature of programming (including the mathematical underpinnings behind STL design), the C + + standard document ISO/IEC 14,882:2003, the C + + Standards Committee proposal and report, and the academic literature on C + +.

Since I'm mainly applying C + +, I'm only on the second to third level. However, C + + is just a part of software development, and language alone cannot cope with business and engineering problems. Readers are advised not to force a few years to "thoroughly learn C + + knowledge", to reach the second floor from the actual work to learn from the experience, interested in slowly continue to learn a higher level of knowledge. Although learning C + + is difficult, it is also quite interesting and satisfying.

For decades, despite the ups and downs of C + +, she relied on its users to continue to get tenacious vitality, I believe that before I retire will not be separated from her, but also want to know more about her, with her into the future.

Give you a clear understanding of C + +

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.