Recent from talks
Nothing was collected or created yet.
| C++ | |
|---|---|
Logo endorsed by the C++ standards committee | |
| Paradigms | Multi-paradigm: procedural, imperative, functional, object-oriented, generic, modular |
| Family | C |
| Designed by | Bjarne Stroustrup |
| Developer | ISO/IEC JTC 1 (Joint Technical Committee 1) / SC 22 (Subcommittee 22) / WG 21 (Working Group 21) |
| First appeared | 1985 |
| Stable release | C++23 (ISO/IEC 14882:2024)
/ 19 October 2024 |
| Preview release | C++26
/ 5 August 2025 |
| Typing discipline | Static, strong, nominative, partially inferred |
| OS | Cross-platform |
| Filename extensions | .C, .cc, .cpp, .cxx, .c++, .h, .H, .hh, .hpp, .hxx, .h++ .cppm, .ixx[1] |
| Website | isocpp |
| Major implementations | |
| GCC, LLVM Clang, Microsoft Visual C++, Embarcadero C++Builder, Intel C++ Compiler, IBM XL C++, EDG | |
| Influenced by | |
| Ada, ALGOL 68,[2] BCPL,[3] C, CLU,[2] F#,[4][a] ML, Mesa,[2] Modula-2,[2] Simula, Smalltalk[2] | |
| Influenced | |
| Ada 95, C#,[5] C99, Carbon, Chapel,[6] Clojure,[7] D, Java,[8] JS++,[9] Lua,[10] Nim,[11] Objective-C++, Perl, PHP, Python,[12] Rust[13] | |
| |
C++[b] is a high-level, general-purpose programming language created by Danish computer scientist Bjarne Stroustrup. First released in 1985 as an extension of the C programming language, adding object-oriented (OOP) features, it has since expanded significantly over time adding more OOP and other features; as of 1997[update]/C++98 standardization, C++ has added functional features, in addition to facilities for low-level memory manipulation for systems like microcomputers or to make operating systems like Linux or Windows, and even later came features like generic programming (through the use of templates). C++ is usually implemented as a compiled language, and many vendors provide C++ compilers, including the Free Software Foundation, LLVM, Microsoft, Intel, Embarcadero, Oracle, and IBM.[14]
C++ was designed with systems programming and embedded, resource-constrained software and large systems in mind, with performance, efficiency, and flexibility of use as its design highlights.[15] C++ has also been found useful in many other contexts, with key strengths being software infrastructure and resource-constrained applications,[15] including desktop applications, video games, servers (e.g., e-commerce, web search, or databases), and performance-critical applications (e.g., telephone switches or space probes).[16]
C++ is standardized by the International Organization for Standardization (ISO), with the latest standard version ratified and published by ISO in October 2024 as ISO/IEC 14882:2024 (informally known as C++23).[17] The C++ programming language was initially standardized in 1998 as ISO/IEC 14882:1998, which was then amended by the C++03, C++11, C++14, C++17, and C++20 standards. The current C++23 standard supersedes these with new features and an enlarged standard library. Before the initial standardization in 1998, C++ was developed by Stroustrup at Bell Labs since 1979 as an extension of the C language; he wanted an efficient and flexible language similar to C that also provided high-level features for program organization.[18] Since 2012, C++ has been on a three-year release schedule[19] with C++26 as the next planned standard.[20]
History
[edit]
In 1979, Bjarne Stroustrup, a Danish computer scientist, began work on "C with Classes", the predecessor to C++.[21] The motivation for creating a new language originated from Stroustrup's experience in programming for his PhD thesis. Stroustrup found that Simula had features that were very helpful for large software development, but the language was too slow for practical use, while BCPL was fast but too low-level to be suitable for large software development. When Stroustrup started working in AT&T Bell Labs, he had the problem of analyzing the UNIX kernel with respect to distributed computing. Remembering his PhD experience, Stroustrup set out to enhance the C language with Simula-like features.[22] C was chosen because it was general-purpose, fast, portable, and widely used. In addition to C and Simula's influences, other languages influenced this new language, including ALGOL 68, Ada, CLU, and ML.[citation needed]
Initially, Stroustrup's "C with Classes" added features to the C compiler, Cpre, including classes, derived classes, strong typing, inlining, and default arguments.[23]

In 1982, Stroustrup started to develop a successor to C with Classes, which he named "C++" (++ being the increment operator in C) after going through several other names. New features were added, including virtual functions, function and operator overloading, references, constants, type-safe free-store memory allocation (new/delete), improved type checking, and BCPL-style single-line comments with two forward slashes (//). Furthermore, Stroustrup developed a new, standalone compiler for C++, Cfront.
In 1984, Stroustrup implemented the first stream input/output library. The idea of providing an output operator rather than a named output function was suggested by Doug McIlroy[2] (who had previously suggested Unix pipes).
In 1985, the first edition of The C++ Programming Language was released, which became the definitive reference for the language, as there was not yet an official standard.[24] The first commercial implementation of C++ was released in October of the same year.[21]
In 1989, C++ 2.0 was released, followed by the updated second edition of The C++ Programming Language in 1991.[25] New features in 2.0 included multiple inheritance, abstract classes, static member functions, const member functions, and protected members. In 1990, The Annotated C++ Reference Manual was published. This work became the basis for the future standard. Later feature additions included templates, exceptions, namespaces, new casts, and a Boolean type.
In 1998, C++98 was released, standardizing the language, and a minor update (C++03) was released in 2003.
After C++98, C++ evolved relatively slowly until, in 2011, the C++11 standard was released, adding numerous new features, enlarging the standard library further, and providing more facilities to C++ programmers. After a minor C++14 update released in December 2014, various new additions were introduced in C++17.[26] After becoming finalized in February 2020,[27] a draft of the C++20 standard was approved on 4 September 2020, and officially published on 15 December 2020.[28][29]
On January 3, 2018, Stroustrup was announced as the 2018 winner of the Charles Stark Draper Prize for Engineering, "for conceptualizing and developing the C++ programming language".[30]
In December 2022, C++ ranked third on the TIOBE index, surpassing Java for the first time in the history of the index. As of November 2024[update], the language ranks second after Python, with Java being in third.[31]
In March 2025, Stroustrup issued a call for the language community to defend it. Since the language allows manual memory management, bugs that represent security risks such as buffer overflow may be introduced in programs when inadvertently misused by the programmer.[32]
Etymology
[edit]According to Stroustrup, "the name signifies the evolutionary nature of the changes from C."[33] This name is credited to Rick Mascitti (mid-1983)[23] and was first used in December 1983. When Mascitti was questioned informally in 1992 about the naming, he indicated that it was given in a tongue-in-cheek spirit. The name comes from C's ++ operator (which increments the value of a variable) and a common naming convention of using "+" to indicate an enhanced computer program.
During C++'s development period, the language had been referred to as "new C" and "C with Classes"[23][34] before acquiring its final name.
Philosophy
[edit]Throughout C++'s life, its development and evolution has been guided by a set of principles:[22]
- It must be driven by actual problems and its features should be immediately useful in real world programs.
- Every feature should be implementable (with a reasonably obvious way to do so).
- Programmers should be free to pick their own programming style, and that style should be fully supported by C++.
- Allowing a useful feature is more important than preventing every possible misuse of C++.
- It should provide facilities for organizing programs into separate, well-defined parts, and provide facilities for combining separately developed parts.
- No implicit violations of the type system (but allow explicit violations; that is, those explicitly requested by the programmer).
- User-created types need to have the same support and performance as built-in types.
- Unused features should not negatively impact created executables (e.g. in lower performance).
- There should be no language beneath C++ (except assembly language).
- C++ should work alongside other existing programming languages, rather than fostering its own separate and incompatible programming environment.
- If the programmer's intent is unknown, allow the programmer to specify it by providing manual control.
Standardization
[edit]| Year | ISO/IEC Standard | Informal name |
|---|---|---|
| 1998 | 14882:1998[35] | C++98 |
| 2003 | 14882:2003[36] | C++03 |
| 2011 | 14882:2011[37] | C++11, C++0x |
| 2014 | 14882:2014[38] | C++14, C++1y |
| 2017 | 14882:2017[39] | C++17, C++1z |
| 2020 | 14882:2020[40] | C++20, C++2a |
| 2024 | 14882:2024[17] | C++23, C++2b |
| TBA | C++26, C++2c |
C++ is standardized by an ISO working group known as JTC1/SC22/WG21. The working group holds three week-long meetings each year.[41] So far, it has published seven revisions of the C++ standard and is currently working on the next revision, C++26.

In 1998, the ISO working group standardized C++ for the first time as ISO/IEC 14882:1998, which is informally known as C++98. In 2003, it published a new version of the C++ standard called ISO/IEC 14882:2003, which fixed problems identified in C++98.
The next major revision of the standard was informally referred to as "C++0x", but it was not released until 2011.[42] C++11 (14882:2011) included many additions to both the core language and the standard library.[37]
In 2014, C++14 (also known as C++1y) was released as a small extension to C++11, featuring mainly bug fixes and small improvements.[43] The Draft International Standard ballot procedures completed in mid-August 2014.[44]
After C++14, a major revision C++17, informally known as C++1z, was completed by the ISO C++ committee in mid July 2017 and was approved and published in December 2017.[45]
As part of the standardization process, ISO also publishes technical reports and specifications:
- ISO/IEC TR 18015:2006[46] on the use of C++ in embedded systems and on performance implications of C++ language and library features,
- ISO/IEC TR 19768:2007[47] (also known as the C++ Technical Report 1) on library extensions mostly integrated into C++11,
- ISO/IEC TR 29124:2010[48] on special mathematical functions, integrated into C++17,
- ISO/IEC TR 24733:2011[49] on decimal floating-point arithmetic,
- ISO/IEC TS 18822:2015[50] on the standard filesystem library, integrated into C++17,
- ISO/IEC TS 19570:2015[51] on parallel versions of the standard library algorithms, integrated into C++17,
- ISO/IEC TS 19841:2015[52] on software transactional memory,
- ISO/IEC TS 19568:2015[53] on a new set of library extensions, some of which are already integrated into C++17,
- ISO/IEC TS 19217:2015[54] on the C++ concepts, integrated into C++20,
- ISO/IEC TS 19571:2016[55] on the library extensions for concurrency, some of which are already integrated into C++20,
- ISO/IEC TS 19568:2017[56] on a new set of general-purpose library extensions,
- ISO/IEC TS 21425:2017[57] on the library extensions for ranges, integrated into C++20,
- ISO/IEC TS 22277:2017[58] on coroutines, integrated into C++20,
- ISO/IEC TS 19216:2018[59] on the networking library,
- ISO/IEC TS 21544:2018[60] on modules, integrated into C++20,
- ISO/IEC TS 19570:2018[61] on a new set of library extensions for parallelism
- ISO/IEC TS 23619:2021[62] on new extensions for reflective programming (reflection),
- ISO/IEC TS 9922:2024[63] on new set of concurrency extensions, and
- ISO/IEC TS 19568:2024[64] on another new set of library extensions.
More technical specifications are in development and pending approval.
Language
[edit]The C++ language has two main components: a direct mapping of hardware features provided primarily by the C subset, and zero-overhead abstractions based on those mappings. Stroustrup describes C++ as "a light-weight abstraction programming language [designed] for building and using efficient and elegant abstractions";[15] and "offering both hardware access and abstraction is the basis of C++. Doing it efficiently is what distinguishes it from other languages."[65]
C++ inherits most of C's syntax. A hello world program that conforms to the C standard is also a valid C++ hello world program. The following is adapted from Bjarne Stroustrup's version of the Hello world program that uses the C++ Standard Library stream facility to write a message to standard output:[66][67][c]
#include <iostream>
int main() {
std::cout << "Hello, world!\n";
}
Since C++23, with the introduction of std::print functions and module std, this can be expressed less verbosely as:
import std;
int main() {
std::println("Hello, world!");
}
Standard library
[edit]
The C++ standard consists of two parts: the core language and the standard library. C++ programmers expect the latter on every major implementation of C++; it includes aggregate types (vectors, linked lists, maps (such as tree maps and hash maps), sets (such as tree sets and hash sets), queues, stacks, arrays, tuples), algorithms (find, for_each, binary_search, random_shuffle, etc.), input/output facilities (I/O streams, for reading from and writing to the console and files), file system manipulation, localisation support, smart pointers for automatic memory management, regular expression support, multi-threading library, atomics support (allowing a variable to be read or written to by at most one thread at a time without any external synchronisation), time utilities (measurement, getting current time, etc.), a system for converting error reporting that does not use C++ exceptions into C++ exceptions, random number generators, and a slightly modified version of the C standard library (to make it comply with the C++ type system).
The design of the C++ standard library, much like the C standard library, is minimalistic, and contains only core features for programming, lacking most of the more specialised features offered by the Java standard library or C# standard library. For more features, some third-party libraries such as Boost libraries and POCO C++ Libraries, which offer additional features, may be used to supplement the standard library.
A large part of the C++ library is based on the Standard Template Library (STL). Useful tools provided by the STL include containers as the collections of objects (such as vectors and lists), iterators that provide array-like access to containers, and algorithms that perform operations such as searching and sorting.
Furthermore, (multi)maps (associative arrays) and (multi)sets are provided, all of which export compatible interfaces. Therefore, using templates it is possible to write generic algorithms that work with any container or on any sequence defined by iterators.
As in C, the features of the library may be accessed by using the #include directive to include a standard header. The C++ Standard Library provides 105 standard headers, of which 27 are deprecated. With the introduction of modules in C++20, these headers may be accessed with import, and in C++23, the entire standard library can now be directly imported as module itself, with import std;. Currently, the C++ standard library provides two modules, std and std.compat (a compatibility module for std which exports C standard library facilities into the global namespace).
The standard incorporates the STL that was originally designed by Alexander Stepanov, who experimented with generic algorithms and containers for many years. When he started with C++, he finally found a language where it was possible to create generic algorithms (e.g., STL sort) that perform even better than, for example, the C standard library qsort, thanks to C++ features like using inlining and compile-time binding instead of function pointers. The standard does not refer to it as "STL", as it is merely a part of the standard library, but the term is still widely used to distinguish it from the rest of the standard library (input/output streams, internationalization, diagnostics, the C library subset, etc.).[68]
Most C++ compilers, and all major ones, provide a standards-conforming implementation of the C++ standard library.
C++ Core Guidelines
[edit]The C++ Core Guidelines[69] are an initiative led by Bjarne Stroustrup, the inventor of C++, and Herb Sutter, the convener and chair of the C++ ISO Working Group, to help programmers write 'Modern C++' by using best practices for the language standards C++11 and newer, and to help developers of compilers and static checking tools to create rules for catching bad programming practices.
The main aim is to efficiently and consistently write type and resource safe C++.
The Core Guidelines were announced[70] in the opening keynote at CPPCon 2015.
The Guidelines are accompanied by the Guideline Support Library (GSL),[71] a header only library of types and functions to implement the Core Guidelines and static checker tools for enforcing Guideline rules.[72]
Compatibility
[edit]To give compiler vendors greater freedom, the C++ standards committee decided not to dictate the implementation of name mangling, exception handling, and other implementation-specific features. The downside of this decision is that object code produced by different compilers is expected to be incompatible. There are, however, attempts to standardize compilers for particular machines or operating systems. For example, the Itanium C++ ABI is processor-independent (despite its name) and is implemented by GCC and Clang.[73]
With C
[edit]C++ is often considered to be a superset of C but this is not strictly true.[74] Most C code can easily be made to compile correctly in C++ but there are a few differences that cause some valid C code to be invalid or behave differently in C++. For example, C allows implicit conversion from void* to other pointer types but C++ does not (for type safety reasons). Also, C++ defines many new keywords, such as new and class, which may be used as identifiers (for example, variable names) in a C program.
Some incompatibilities have been removed by the 1999 revision of the C standard (C99), which now supports C++ features such as line comments (//) and declarations mixed with code. On the other hand, C99 introduced a number of new features that C++ did not support that were incompatible or redundant in C++, such as variable-length arrays, native complex-number types (however, the std::complex class in the C++ standard library provides similar functionality, although not code-compatible), designated initializers, compound literals, and the restrict keyword.[75] Some of the C99-introduced features were included in the subsequent version of the C++ standard, C++11 (out of those which were not redundant).[76][77][78] However, the C++11 standard introduces new incompatibilities, such as disallowing assignment of a string literal to a character pointer, which remains valid C.
To intermix C and C++ code, any function declaration or definition that is to be called from/used both in C and C++ must be declared with C linkage by placing it within an extern "C" {/*...*/} block. Such a function may not rely on features depending on name mangling (i.e., function overloading).
Inline assembly
[edit]Programs developed in C or C++ often utilize inline assembly to take advantage of its low-level functionalities, greater speed, and enhanced control compared to high-level programming languages[79][80] when optimizing for performance is essential. C++ provides support for embedding assembly language using asm declarations,[81] but the compatibility of inline assembly varies significantly between compilers and architectures. Unlike high-level language features such as Python or Java, assembly code is highly dependent on the underlying processor and compiler implementation.
Variations across compilers
[edit]Different C++ compilers implement inline assembly in distinct ways.
- GCC (GNU Compiler Collection) and Clang:[82] Use the GCC extended inline assembly syntax. Using
__asm__keyword instead ofasmwhen writing code that can be compiled with-ansiand-stdoptions, which allows specifying input/output operands and clobbered registers. This approach is widely adopted, including by Intel[83] and IBM[84] compilers. - MSVC (Microsoft Visual C++): The inline assembler is built into the compiler. Previously supported inline assembly via the
__asmkeyword, but this support has been removed in 64-bit mode, requiring separate .asm modules instead.[85] - TI ARM Clang and Embedded Compilers:[86] Some embedded system compilers, like Texas Instruments' TI Arm Clang, allow inline assembly but impose stricter rules to avoid conflicts with register conventions and calling conventions.
Interoperability between C++ and Assembly
[edit]C++ provides two primary methods of integrating ASM code.
1. Standalone assembly files – Assembly code is written separately and linked with C++ code.[87]
2. Inline assembly – Assembly code is embedded within C++ code using compiler-specific extensions.
See also
[edit]- Carbon (programming language) — development at Google to potentially be a successor to C++
- Comparison of programming languages
- List of C++ compilers
- List of C++ software and tools
- List of C++ programming books
- Outline of C++
- Category:C++ libraries
Notes
[edit]- ^ For the idea of the C++20 stackless coroutines.
- ^ Pronounced /ˈsiː plʌs plʌs/ SEE PLUSS PLUSS and sometimes abbreviated as CPP or CXX.
- ^ This code is adapted from Bjarne Stroustrup's errata page (p. 633). He addresses the use of
'\n'rather thanstd::endl. Also see Can I write "void main()"? Archived 2 July 2020 at the Wayback Machine for an explanation of the implicitreturn 0;in themainfunction. This implicit return is not available in other functions.
References
[edit]- ^ "Overview of modules in C++". Microsoft. 24 April 2023.
- ^ a b c d e f Stroustrup, Bjarne (1996). "A history of C++: 1979-1991". History of programming languages---II. ACM. pp. 699–769. doi:10.1145/234286.1057836.
- ^ Stroustrup, Bjarne (16 December 2021). "C++20: Reaching for the Aims of C++ - Bjarne Stroustrup - CppCon 2021". CppCon. Archived from the original on 30 December 2021. Retrieved 30 December 2021.
- ^ Stroustrup, Bjarne (12 June 2020). "Thriving in a crowded and changing world: C++ 2006–2020". Proceedings of the ACM on Programming Languages. 4 (HOPL). Association for Computing Machinery (ACM): 1–168. doi:10.1145/3386320. ISSN 2475-1421. S2CID 219603741.
- ^ Naugler, David (May 2007). "C# 2.0 for C++ and Java programmer: conference workshop". Journal of Computing Sciences in Colleges. 22 (5).
Although C# has been strongly influenced by Java it has also been strongly influenced by C++ and is best viewed as a descendant of both C++ and Java.
- ^ "Chapel spec (Acknowledgements)" (PDF). Cray Inc. 1 October 2015. Archived (PDF) from the original on 24 June 2018. Retrieved 14 January 2016.
- ^ Fogus, Michael. "Rich Hickey Q&A". Code Quarterly. Archived from the original on 11 January 2017. Retrieved 11 January 2017.
- ^ Harry. H. Chaudhary (28 July 2014). "Cracking The Java Programming Interview :: 2000+ Java Interview Que/Ans". Archived from the original on 27 May 2021. Retrieved 29 May 2016.
- ^ Roger Poon (1 May 2017). "Scaling JS++: Abstraction, Performance, and Readability". Archived from the original on 11 May 2020. Retrieved 21 April 2020.
- ^ "The evolution of an extension language: a history of Lua". www.lua.org. Retrieved 4 January 2023.
- ^ "FAQ Nim Programming Language". Archived from the original on 11 July 2017. Retrieved 21 April 2020.
- ^ "9. Classes — Python 3.6.4 documentation". docs.python.org. Archived from the original on 23 October 2012. Retrieved 9 January 2018.
- ^ "Influences - The Rust Reference". doc.rust-lang.org. Retrieved 4 January 2023.
- ^ Stroustrup, Bjarne (1997). "1". The C++ Programming Language (Third ed.). Addison-Wesley. ISBN 0-201-88954-4. OCLC 59193992.
- ^ a b c Stroustrup, B. (6 May 2014). "Lecture:The essence of C++. University of Edinburgh". YouTube. Archived from the original on 28 April 2015. Retrieved 12 June 2015.
- ^ Stroustrup, Bjarne (17 February 2014). "C++ Applications". stroustrup.com. Archived from the original on 4 April 2021. Retrieved 5 May 2014.
- ^ a b "ISO/IEC 14882:2024". International Organization for Standardization. Retrieved 21 October 2020.
- ^ "Bjarne Stroustrup's Homepage". www.stroustrup.com. Archived from the original on 14 May 2019. Retrieved 15 May 2013.
- ^ "C++ IS schedule" (PDF). Archived (PDF) from the original on 10 August 2020. Retrieved 9 August 2020.
- ^ "C++; Where it's heading". Archived from the original on 3 December 2018. Retrieved 3 December 2018.
- ^ a b Stroustrup, Bjarne (7 March 2010). "Bjarne Stroustrup's FAQ: When was C++ invented?". stroustrup.com. Archived from the original on 6 February 2016. Retrieved 16 September 2010.
- ^ a b Stroustrup, Bjarne. "Evolving a language in and for the real world: C++ 1991-2006" (PDF). Archived (PDF) from the original on 20 November 2007. Retrieved 14 August 2013.
- ^ a b c Stroustrup, Bjarne. "A History of C ++ : 1979− 1991" (PDF). Archived (PDF) from the original on 2 February 2019. Retrieved 18 July 2013.
- ^ Stroustrup, Bjarne. "The C++ Programming Language" (First ed.). Archived from the original on 9 August 2012. Retrieved 16 September 2010.
- ^ Stroustrup, Bjarne. "The C++ Programming Language" (Second ed.). Archived from the original on 9 August 2012. Retrieved 16 September 2010.
- ^ Sutter, Herb (30 June 2016). "Trip report: Summer ISO C++ standards meeting (Oulu)". herbsutter.com. Archived from the original on 8 October 2016.
the next standard after C++17 will be C++20
- ^ Dusíková, Hana (6 November 2019). "N4817: 2020 Prague Meeting Invitation and Information" (PDF). Archived (PDF) from the original on 29 December 2019. Retrieved 13 February 2020.
- ^ "Current Status". isocpp.org. Archived from the original on 8 September 2020. Retrieved 7 September 2020.
- ^ "C++20 Approved -- Herb Sutter". isocpp.org. Archived from the original on 11 September 2020. Retrieved 8 September 2020.
- ^ "Computer Science Pioneer Bjarne Stroustrup to Receive the 2018 Charles Stark Draper Prize for Engineering" (Press release). National Academy of Engineering. 3 January 2018. Archived from the original on 3 January 2018. Retrieved 14 December 2021.
- ^ TIOBE (November 2024). "TIOBE Index for November 2024". TIOBE.com. TIOBE Company. Archived from the original on 18 November 2024. Retrieved 18 November 2024.
- ^ Claburn, Thomas (2 March 2025). "C++ creator calls for help to defend programming language from 'serious attacks'". The Register. Retrieved 5 March 2025.
- ^ "Bjarne Stroustrup's FAQ – Where did the name "C++" come from?". Archived from the original on 6 February 2016. Retrieved 16 January 2008.
- ^ "C For C++ Programmers". Northeastern University. Archived from the original on 17 November 2010. Retrieved 7 September 2015.
- ^ "ISO/IEC 14882:1998". International Organization for Standardization. Archived from the original on 15 January 2017. Retrieved 23 November 2018.
- ^ "ISO/IEC 14882:2003". International Organization for Standardization. Archived from the original on 13 August 2021. Retrieved 23 November 2018.
- ^ a b "ISO/IEC 14882:2011". International Organization for Standardization. Archived from the original on 27 May 2016. Retrieved 23 November 2018.
- ^ "ISO/IEC 14882:2014". International Organization for Standardization. Archived from the original on 29 April 2016. Retrieved 23 November 2018.
- ^ "ISO/IEC 14882:2017". International Organization for Standardization. Archived from the original on 29 January 2013. Retrieved 2 December 2017.
- ^ "ISO/IEC 14882:2020". International Organization for Standardization. Archived from the original on 16 December 2020. Retrieved 16 December 2020.
- ^ "Meetings and Participation". News, Status & Discussion About Standard C++. The Standard C++ Foundation. Retrieved 6 September 2025.
- ^ "We have an international standard: C++0x is unanimously approved". Sutter's Mill. 12 August 2011. Archived from the original on 28 June 2018. Retrieved 23 November 2018.
- ^ "The Future of C++". Archived from the original on 23 October 2018. Retrieved 23 November 2018 – via channel9.msdn.com.
- ^ "We have C++14! : Standard C++". isocpp.org. Archived from the original on 19 August 2014. Retrieved 19 August 2014.
- ^ Sutter, Herb (15 July 2017). "Trip report: Summer ISO C++ standards meeting (Toronto)". Archived from the original on 6 August 2017. Retrieved 4 August 2017.
- ^ "ISO/IEC TR 18015:2006". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TR 19768:2007". International Organization for Standardization. Archived from the original on 4 March 2016. Retrieved 15 February 2019.
- ^ "ISO/IEC TR 29124:2010". International Organization for Standardization. Archived from the original on 12 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TR 24733:2011". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 18822:2015". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 19570:2015". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 19841:2015". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 19568:2015". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 19217:2015". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 19571:2016". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 19568:2017". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 21425:2017". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 22277:2017". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 19216:2018". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 21544:2018". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 19570:2018". International Organization for Standardization. Archived from the original on 15 January 2019. Retrieved 15 February 2019.
- ^ "ISO/IEC TS 23619:2021". International Organization for Standardization. Archived from the original on 15 December 2018. Retrieved 11 October 2021.
- ^ "ISO/IEC TS 9922:2024". International Organization for Standardization. Archived from the original on 1 April 2025. Retrieved 1 April 2025.
- ^ "ISO/IEC TS 19568:2024". International Organization for Standardization. Archived from the original on 25 February 2025. Retrieved 1 April 2025.
- ^ B. Stroustrup (interviewed by Sergio De Simone) (30 April 2015). "Stroustrup: Thoughts on C++17 - An Interview". Archived from the original on 8 July 2015. Retrieved 8 July 2015.
- ^ Stroustrup, Bjarne (2000). The C++ Programming Language (Special ed.). Addison-Wesley. p. 46. ISBN 0-201-70073-5.
- ^ Stroustrup, Bjarne. "Open issues for The C++ Programming Language (3rd Edition)". Archived from the original on 5 May 2014. Retrieved 5 May 2014.
- ^ Graziano Lo Russo (2008). "An Interview with A. Stepanov". stlport.org. Archived from the original on 4 March 2009. Retrieved 8 October 2015.
- ^ "C++ Core Guidelines". isocpp.github.io. Archived from the original on 16 February 2020. Retrieved 9 February 2020.
- ^ "Bjarne Stroustrup announces C++ Core Guidelines : Standard C++". isocpp.org. Archived from the original on 11 May 2020. Retrieved 31 March 2020.
- ^ "microsoft/GSL". 18 July 2021. Archived from the original on 18 July 2021. Retrieved 18 July 2021 – via GitHub.
- ^ "Using the C++ Core Guidelines checkers". Microsoft Learn. Archived from the original on 13 August 2021. Retrieved 31 March 2020.
- ^ "C++ ABI Summary". 20 March 2001. Archived from the original on 10 July 2018. Retrieved 30 May 2006.
- ^ "Bjarne Stroustrup's FAQ – Is C a subset of C++?". Archived from the original on 6 February 2016. Retrieved 5 May 2014.
- ^ "C9X – The New C Standard". Archived from the original on 21 June 2018. Retrieved 27 December 2008.
- ^ "C++0x Support in GCC". Archived from the original on 21 July 2010. Retrieved 12 October 2010.
- ^ "C++0x Core Language Features In VC10: The Table". Archived from the original on 21 August 2010. Retrieved 12 October 2010.
- ^ "Clang - C++98, C++11, and C++14 Status". Clang.llvm.org. 12 May 2013. Archived from the original on 4 July 2013. Retrieved 10 June 2013.
- ^ Bokil, Milind A. (2021). "Writing Assembly Routines within C/C++ and Java Programs". ResearchGate. Retrieved 1 April 2025.
- ^ De Vilhena, Paulo Emílio; Lahav, Ori; Vafeiadis, Viktor; Raad, Azalea (2024). "Extending the C/C++ Memory Model with Inline Assembly". Proceedings of the ACM on Programming Languages. 8: 1081–1107. arXiv:2408.17208. doi:10.1145/3689749.
- ^ cppreference.com contributors. "asm declaration". cppreference.com. Retrieved 1 April 2025.
- ^ "Extended Asm (Using the GNU Compiler Collection)". GCC Online Documentation. GNU Project. Retrieved 1 April 2025.
- ^ Intel Corporation. "Inline Assembly". Intel® C++ Compiler Classic Developer Guide and Reference, Version 2021.9. Retrieved 1 April 2025.
- ^ IBM. "Inline assembly statements (IBM extension)". IBM Documentation. Retrieved 1 April 2025.
- ^ "Inline Assembler Overview". Microsoft Learn. Microsoft. Retrieved 1 April 2025.
- ^ "Interfacing C and C++ With Assembly Language". Texas Instruments. Texas Instruments Incorporated. 23 February 2025. Retrieved 1 April 2025.
- ^ "C++ to ASM linkage in GCC". OSDev Wiki. Retrieved 1 April 2025.
Further reading
[edit]- Abrahams, David; Gurtovoy, Aleksey (2005). C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond. Addison-Wesley. ISBN 0-321-22725-5.
- Alexandrescu, Andrei (2001). Modern C++ Design: Generic Programming and Design Patterns Applied. Addison-Wesley. ISBN 0-201-70431-5.
- Alexandrescu, Andrei; Sutter, Herb (2004). C++ Design and Coding Standards: Rules and Guidelines for Writing Programs. Addison-Wesley. ISBN 0-321-11358-6.
- Becker, Pete (2006). The C++ Standard Library Extensions : A Tutorial and Reference. Addison-Wesley. ISBN 0-321-41299-0.
- Brokken, Frank (2010). C++ Annotations. University of Groningen. ISBN 978-90-367-0470-0. Archived from the original on 28 April 2010. Retrieved 28 April 2010.
- Coplien, James O. (1994) [reprinted with corrections, original year of publication 1992]. Advanced C++: Programming Styles and Idioms. Addison-Wesley. ISBN 0-201-54855-0.
- Dewhurst, Stephen C. (2005). C++ Common Knowledge: Essential Intermediate Programming. Addison-Wesley. ISBN 0-321-32192-8.
- Information Technology Industry Council (15 October 2003). Programming languages – C++ (Second ed.). Geneva: ISO/IEC. 14882:2003(E).
- Josuttis, Nicolai M. (2012). The C++ Standard Library, A Tutorial and Reference (Second ed.). Addison-Wesley. ISBN 978-0-321-62321-8.
- Koenig, Andrew; Moo, Barbara E. (2000). Accelerated C++ – Practical Programming by Example. Addison-Wesley. ISBN 0-201-70353-X.
- Lippman, Stanley B.; Lajoie, Josée; Moo, Barbara E. (2011). C++ Primer (Fifth ed.). Addison-Wesley. ISBN 978-0-321-71411-4.
- Lippman, Stanley B. (1996). Inside the C++ Object Model. Addison-Wesley. ISBN 0-201-83454-5.
- Meyers, Scott (2005). Effective C++ (Third ed.). Addison-Wesley. ISBN 0-321-33487-6.
- Stroustrup, Bjarne (2013). The C++ Programming Language (Fourth ed.). Addison-Wesley. ISBN 978-0-321-56384-2.
- Stroustrup, Bjarne (1994). The Design and Evolution of C++. Addison-Wesley. ISBN 0-201-54330-3.
- Stroustrup, Bjarne (2014). Programming: Principles and Practice Using C++ (Second ed.). Addison-Wesley. ISBN 978-0-321-99278-9.
- Sutter, Herb (2001). More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions. Addison-Wesley. ISBN 0-201-70434-X.
- Sutter, Herb (2004). Exceptional C++ Style. Addison-Wesley. ISBN 0-201-76042-8.
- Vandevoorde, David; Josuttis, Nicolai M. (2003). C++ Templates: The complete Guide. Addison-Wesley. ISBN 0-201-73484-2.
External links
[edit]- JTC1/SC22/WG21 – the ISO/IEC C++ Standard Working Group
- Standard C++ Foundation – a non-profit organization that promotes the use and understanding of standard C++. Bjarne Stroustrup is a director of the organization.
- C++ Keywords
- C++ Expressions
- C++ Operator Precedence
History
Origins and Development
C++ originated in the late 1970s at Bell Labs, where Danish computer scientist Bjarne Stroustrup was working on distributed systems simulations. In April 1979, Stroustrup began developing an extension to the C programming language to incorporate object-oriented features, initially dubbing the project "C with Classes." This effort stemmed from his need for a tool that combined C's low-level efficiency and portability with higher-level abstractions for organizing complex programs, particularly for his research on the UNIX kernel.[3] The design of C with Classes drew heavily from existing languages to address limitations in C for large-scale software development. Simula provided the foundational concepts of classes and inheritance, enabling structured data abstraction and simulation hierarchies that Stroustrup had encountered during his PhD work at Cambridge University. Smalltalk influenced the object-oriented paradigm through its emphasis on dynamic subclassing and message passing, though C with Classes retained C's static typing and performance focus to avoid runtime overhead. By October 1979, Stroustrup implemented a basic preprocessor called Cpre, which evolved into a full implementation supporting derived classes, access control (public/private), and constructors by early 1980. The first technical report describing these features, titled "Classes: An Abstract Data Type Facility for the C Language," was published internally at Bell Labs in April 1980.[3] Development progressed through the early 1980s with refinements including inline functions, default arguments, and operator overloading added in 1981, as detailed in Stroustrup's SIGPLAN Notices paper in 1982. In 1982, Stroustrup shifted from a preprocessor to a dedicated compiler, Cfront, which translated C++ code into C for compilation, ensuring portability across systems like the DEC PDP/11 and VAX. The name "C++" was coined in late 1983 by colleague Rick Mascitti, reflecting the incremental evolution from C. The first public release, version 1.0, occurred in October 1985, introducing multiple inheritance, exceptions, virtual functions, references, and the const qualifier, alongside the publication of Stroustrup's seminal book, The C++ Programming Language. Cfront's initial versions were used internally at Bell Labs before this commercial rollout, marking C++'s transition from a research tool to a viable systems programming language.[3][11][12]Etymology
The name "C++" was coined by Rick Mascitti, a colleague of Bjarne Stroustrup at Bell Labs, in the summer of 1983.[13] This choice drew directly from the C programming language's increment operator "++", symbolizing the new language as an evolutionary extension and successor to C, much like incrementing a value by one.[13] The name was selected during internal discussions for its brevity, multiple positive interpretations (such as "next" or "successor"), and avoidance of phrasing like "adjective C", with the first public use occurring in December 1983 in Stroustrup's publications.[13] The language is officially pronounced "see plus plus", reflecting a literal reading of the symbols rather than alternatives like "see double plus".[13] Abbreviations such as "Cpp" were deliberately avoided in favor of the full "C++" to prevent potential confusion with file extensions like .cp, though the primary emphasis remained on the symbolic and phonetic clarity of the chosen name.[13] During the naming process at Bell Labs, several alternatives were considered but rejected. "C+" was dismissed because it resembled a syntax error in C (where a unary plus requires spacing) and was already in use by an unrelated programming language.[13] "++C", the post-increment variant, served as a runner-up and was favored by some for its semantic nuance among C enthusiasts, but "C++" (pre-increment) ultimately prevailed for its alignment with the language's forward-looking evolution.[13]Early Adoption and Milestones
The publication of Bjarne Stroustrup's The C++ Programming Language in October 1985 marked a pivotal moment in raising awareness of the language, providing the first comprehensive reference and tutorial that facilitated its dissemination beyond Bell Labs.[3] This first edition, released alongside the commercial availability of the Cfront compiler, helped transition C++ from an experimental extension of C to a viable tool for software development, with an estimated 500 users by the end of 1985 growing to 2,000 by 1986.[3] Early commercial compilers accelerated adoption, beginning with the free GNU C++ release 1.13 in December 1987, followed by Zortech C++ in June 1988, which was among the first native-code compilers not reliant on translating to C.[3] Borland's Turbo C++ 1.0, launched in May 1990, further popularized the language through its integrated development environment and rapid compilation, becoming a staple for MS-DOS programming and contributing to Borland shipping 500,000 units by October 1991.[3] These tools, alongside AT&T's Cfront 2.0 in June 1989—which introduced multiple inheritance—enabled broader experimentation in object-oriented systems programming.[3] A significant milestone came in March 1990 with the publication of The Annotated C++ Reference Manual (ARM) by Margaret A. Ellis and Bjarne Stroustrup, which served as the foundational specification for the language and was adopted as the basis for standardization efforts.[3] The formation of the ANSI X3J16 committee in December 1989, followed by the ISO WG21 working group in June 1991, addressed growing needs for a unified definition amid proliferating implementations.[3] By the mid-1990s, C++ saw widespread adoption in systems programming at major companies, including AT&T—where it originated for enhancing UNIX development—and Microsoft, which integrated it into Windows via Visual C++ starting in 1993 for performance-critical applications like operating systems and games.[14] This era solidified C++ as the dominant object-oriented language, powering large-scale software at these organizations despite its roots in efficiency-focused extensions to C.[14] However, the pre-standardization period was marked by challenges from multiple incompatible implementations, such as variations in Cfront, GNU, and vendor-specific extensions, which led to portability issues and debates over compatibility with ANSI C—ultimately driving the push for ISO standardization to ensure interoperability.[3] These incompatibilities, including differences in name mangling and exception handling, highlighted the need for a common reference like the ARM to stabilize the ecosystem.[3]Design Philosophy
Core Principles
C++ adheres to the zero-overhead principle, a foundational design tenet articulated by its creator, Bjarne Stroustrup, which ensures that no language feature imposes runtime or space overhead unless explicitly utilized by the programmer.[15] This principle manifests in the compiler's ability to optimize away unused abstractions, such as virtual functions or exception handling, resulting in code that performs equivalently to hand-written C when low-level control is desired.[16] By avoiding mandatory costs for features like garbage collection or runtime type checking, C++ enables developers to achieve high performance without sacrificing expressiveness.[15] Central to C++'s architecture is its support for multi-paradigm programming, allowing the integration of procedural, object-oriented, and generic styles without enforcing a singular approach, all while prioritizing efficiency and fine-grained control over system resources.[17] This flexibility stems from Stroustrup's vision of a language that accommodates diverse programming needs, from systems programming to high-level application development, ensuring that abstractions enhance rather than hinder performance.[18] The "pay only for what you use" ethos reinforces this by guaranteeing that the runtime cost of any paradigm or feature is proportional to its invocation, aligning with the zero-overhead goal.[15] Resource Acquisition Is Initialization (RAII) serves as a core idiom in C++, binding the lifecycle of resources—such as memory, files, or locks—to the scope of objects through constructors and destructors, thereby ensuring deterministic cleanup and exception safety without additional runtime mechanisms.[19] Developed by Stroustrup and Andrew Koenig in the late 1980s, RAII exemplifies C++'s philosophy of leveraging low-level control akin to C for direct hardware access while introducing high-level abstractions that promote safe and efficient resource management.[20] This approach allows programmers to write robust code that scales from embedded systems to large-scale simulations, maintaining the language's commitment to both power and reliability.[21]Programming Paradigms Supported
C++ is a multi-paradigm programming language designed to support a variety of programming styles, allowing developers to choose approaches that best fit the problem at hand while maintaining efficiency and flexibility.[2] This design enables seamless integration of different paradigms within the same codebase, reflecting its evolution from C to incorporate advanced abstractions without sacrificing performance.[22] Procedural programming in C++ directly inherits from its C roots, emphasizing structured code organization through functions, control structures, and data aggregates like arrays and structs. This paradigm focuses on step-by-step procedures to manipulate data, providing a low-level, efficient foundation for systems programming and algorithmic implementations.[13] Compatibility with C ensures that existing procedural code can be compiled and extended in C++, supporting modular development via separate compilation units.[23] Object-oriented programming is a core paradigm in C++, facilitated by classes that encapsulate data and behavior, inheritance for code reuse, polymorphism through virtual functions, and encapsulation to protect internal state. These features, inspired by Simula, allow for modeling complex systems with hierarchies of related types, promoting maintainability and extensibility in large-scale applications.[13] For instance, abstract base classes enable interface definitions that derived classes implement, supporting runtime decisions based on object types.[2] Generic programming is supported through templates, which parameterize code over types, values, or algorithms, enabling type-safe, reusable components without runtime overhead. This approach, central to the Standard Template Library, allows writing algorithms that operate on arbitrary container types, fostering metaprogramming techniques like compile-time computations.[22] Templates promote abstraction at the type level, where a single function or class definition can instantiate for multiple types, enhancing code generality and performance.[23] Functional programming elements have been progressively integrated into C++, particularly with the introduction of lambda expressions in C++11, which allow inline definition of anonymous functions for concise expression of higher-order functions and closures. These features support functional styles such as passing functions as arguments or returning them from other functions, facilitating immutable data handling and algorithmic composition without side effects.[24] Later standards like C++14 and C++17 refined lambdas with generic capture and constexpr support, bridging functional paradigms with C++'s zero-overhead principle.[25]Key Design Goals
One of the primary design goals of C++ was to ensure high compatibility with C, enabling seamless integration and reuse of existing C codebases. This compatibility allows C++ programs to incorporate C libraries and code without significant modifications, facilitating a gradual transition for developers and leveraging the vast ecosystem of C software. As stated by Bjarne Stroustrup, "C++ was deliberately designed to support C-style low-level programming," with the ideal of full compatibility to maximize sharing of libraries, tools, and knowledge across the C/C++ community.[26] This design choice supports mixed-language projects, where C++ extends C's capabilities while maintaining source and binary compatibility where possible.[26] C++ was engineered for performance comparable to hand-written assembly code, particularly targeting systems programming and embedded environments with strict resource constraints. Efficiency remains a foundational principle, encapsulated in the zero-overhead abstraction rule, where users incur no runtime costs for unused features, allowing generated code to match or exceed equivalent C implementations through compiler optimizations.[27] For instance, features like templates enable compile-time polymorphism without runtime penalties, making C++ suitable for real-time systems and hardware drivers that require minimal overhead and direct hardware access.[27] Stroustrup emphasized that "an algorithm is absolutely efficient if as efficient as nongeneric assembly; C++ comes very close to this goal."[27] To support large-scale software development, C++ incorporates mechanisms for modularity and abstraction that help manage complexity in extensive codebases. Classes, inheritance, and abstract base classes provide robust interfaces for services, allowing implementations to evolve without affecting dependent code, thus promoting maintainability and reusability.[28] Stroustrup noted that the language aims "to control complexity" through elegant abstractions like resource management via constructors and destructors, enabling developers to build and maintain large programs with suitable libraries.[29] This focus on organizing code for easier evolution supports multi-paradigm programming in enterprise-level applications.[28] Portability across diverse hardware architectures and operating systems was a key objective, achieved by building on C's foundation and avoiding platform-specific dependencies in the core language. C++'s design facilitates code that compiles and runs consistently across systems, with standardization ensuring a unified specification that compilers must adhere to.[29] Features like the standard library abstract common operations, reducing reliance on vendor-specific extensions, while direct hardware access remains available for low-level needs without compromising broader portability.[27] As Stroustrup described, the goals include providing "direct access to hardware" in a way that supports efficient code across varied environments.[29]Standardization and Evolution
ISO Standardization Process
The ISO/IEC JTC1/SC22/WG21 working group, responsible for the international standardization of the C++ programming language, was formed in 1990-91 as a subgroup under the broader ISO/IEC JTC1/SC22 subcommittee for programming languages and environments.[30] This establishment followed initial national efforts, such as the ANSI X3J16 committee in the United States, to harmonize C++ development globally through ISO procedures.[30] National bodies affiliated with ISO/IEC JTC1 play a central role in WG21, providing accredited delegates who represent their countries' interests and vote on proposals. For instance, the United States participates via INCITS (InterNational Committee for Information Technology Standards), whose PL22.16 task group handles technical contributions and ensures alignment with domestic needs before forwarding positions to WG21.[31] Over 20 nations, including Canada, China, France, Germany, Japan, and the United Kingdom, contribute through similar bodies, fostering consensus-driven decisions.[30] The standardization cycle begins with the submission of working papers—detailed proposals outlining features, rationales, examples, and alternatives—which are reviewed during WG21's triannual meetings.[32] Approved elements are incorporated into evolving working drafts, which subgroups like the Core Working Group (CWG) and Library Working Group (LWG) refine for technical accuracy before plenary approval. These drafts progress to Committee Draft (CD) status for national body ballot, inviting comments to resolve ambiguities or inconsistencies.[32] Public comments from national bodies are addressed iteratively to build consensus, after which the document advances to Draft International Standard (DIS) for a two-month vote requiring at least two-thirds approval from participating members.[32] If passed, it becomes Final Draft International Standard (FDIS) for a final confirmatory ballot, typically with minimal changes, leading to publication as an International Standard.[32] Leadership in WG21 has been shaped by key figures, including Bjarne Stroustrup, the language's creator and a founding member who served as chair emeritus of the Evolution Working Group, guiding early feature directions.[33] Herb Sutter currently serves as convener, responsible for chairing meetings, determining consensus, and managing the overall process in coordination with vice-convener John Spicer and secretary Nina Ranns.[30] Post-publication, the process addresses defects through formal reports submitted to issue-tracking lists maintained by CWG and LWG.[32] Critical issues may prompt immediate guidance via papers or evolution toward technical corrigenda—amendments correcting errors without altering the standard's scope—which require national body approval similar to the initial cycle.[32] This ensures ongoing maintenance while preserving stability for implementations.[32]Major Revisions (C++98 to C++23)
The first International Standard for C++, designated ISO/IEC 14882:1998 and commonly referred to as C++98, formalized the language developed by Bjarne Stroustrup and others at Bell Labs since the early 1980s.[34] This standard introduced core object-oriented features such as templates for generic programming, the Standard Template Library (STL) including containers like vectors and lists, exception handling for error management, and namespaces to avoid name conflicts. It established C++ as a multi-paradigm language extending C with abstract data types, inheritance, and polymorphism, while maintaining backward compatibility with C code where possible.[35] C++11, published as ISO/IEC 14882:2011, represented a major modernization effort, incorporating features developed over the previous decade to address limitations in expressiveness and performance. Key additions included theauto keyword for type deduction, lambda expressions for inline function objects, smart pointers like std::unique_ptr and std::shared_ptr for automatic memory management, move semantics to enable efficient resource transfer, and constexpr for compile-time computations.[36] These enhancements improved support for concurrency, generic programming, and resource management, making C++ more suitable for modern hardware and reducing reliance on manual memory handling.[37]
C++14 (ISO/IEC 14882:2014) and C++17 (ISO/IEC 14882:2017) focused on refinements and completions to C++11, with C++14 providing incremental improvements such as variable templates for parameterized non-type values, generic lambdas with auto parameters, and relaxed constexpr rules allowing more operations at compile time.[38] C++17 built on this with structured bindings for unpacking aggregates, the filesystem library for directory and file operations, parallel algorithms in the STL for multi-core execution, and fold expressions for variadic template reductions.[39] These releases emphasized usability and performance, introducing features like inline variables to avoid one-definition-rule issues and if constexpr for conditional compilation.[40]
C++20, formalized in ISO/IEC 14882:2020, introduced transformative capabilities including concepts for constraining template parameters, modules to replace header-based includes and reduce compilation times, coroutines for asynchronous programming, the ranges library for composable sequence operations, and three-way comparison (<=>) for simplified operator definitions.[41] These features enhanced modularity, expressiveness in generic code, and support for concurrent and functional styles, addressing long-standing requests from the developer community.[42]
C++23, ratified as ISO/IEC 14882:2024 and published in 2024 following technical completion in February 2023, continued the trend of targeted enhancements with pattern matching via inspection operators for destructuring data structures, std::expected for error-handling monads similar to Rust's Result type, and various library simplifications such as multidimensional subscript operators and improved Unicode support.[43] This standard prioritized completing unfinished C++20 work, like the std module, while adding utilities for safer and more efficient code, resulting in a more polished language for systems and application development.[44]
Upcoming Developments
The development of C++26 represents the next phase in the language's evolution following C++23, with the ISO C++ standards committee (WG21) focusing on enhancing introspection, reliability, and expressiveness while addressing contemporary programming demands. Key proposals target static reflection to enable compile-time metaprogramming advancements, including metaclasses that facilitate library evolution by allowing programmatic generation and customization of types. For instance, the Reflection for C++26 proposal introduces a foundational set of reflection primitives, such as the^ operator for accessing type information at compile time, enabling more dynamic and safer library implementations without runtime overhead.[45] Similarly, contracts are being integrated to provide enforceable preconditions, postconditions, and assertions, improving code safety and documentation through declarative specifications that can be selectively enforced at compile or runtime.[46]
Further enhancements to pattern matching build on C++23's inspector-based matching by introducing more comprehensive expression forms, such as the match statement, to simplify destructuring and control flow in generic code. Active WG21 papers also emphasize safer concurrency models, including concurrent queues for lock-free data structures and pointer lifetime-end mechanisms to prevent use-after-free errors in multithreaded environments. These efforts aim to evolve the standard library with hardened primitives that reduce common pitfalls while supporting high-performance applications.[47][48][49]
Following the November 2025 meeting in Kona, Hawaii, which completed the first of two final fit-and-finish meetings, contracts were retained with two bug fixes adopted, while reflection and pattern matching advanced beyond feature freeze for inclusion in C++26. Safety profiles saw improvements, such as refined handling of erroneous behavior to poison only uninitialized values rather than the entire program. Trivial relocatability was removed due to implementation issues.[50]
A primary challenge in C++26's design is balancing backward compatibility with the integration of modern paradigms, such as those required for AI and machine learning workloads, where the committee must ensure new features like reflection and concurrency enhancements do not disrupt existing codebases while enabling efficient GPU acceleration and parallel tensor operations through study group SG19's contributions. Core safety profiles, for example, propose opt-in restrictions to mitigate memory safety issues without breaking legacy code.
The timeline for C++26 includes the final committee session in March 2026 in Croydon, London, to incorporate remaining feedback and finalize the specification, with publication expected in 2026.[50] This schedule aligns with WG21's triennial release cadence, allowing implementers time to integrate features into compilers like GCC and Clang ahead of widespread adoption.
Language Features
Syntax and Semantics
C++ syntax defines the structure of valid programs through a context-free grammar, while semantics specify the meaning and behavior of those programs, ensuring portability across implementations.[51] The language's lexical analysis breaks source code into tokens during translation phase 3, ignoring whitespace except as a separator between tokens.[52] Tokens fall into five categories: identifiers, keywords, literals, operators, and punctuators (also called separators). Keywords, such asint and if, are reserved and cannot be used as identifiers, while literals represent constant values like integers (42) or strings ("hello").[53]
Comments in C++ serve to annotate code without affecting execution and are treated as whitespace after processing. Traditional comments use /* to start and */ to end, spanning multiple lines without nesting, whereas single-line comments begin with // and extend to the end of the line.[54] Identifiers name entities like variables or functions and must begin with a Unicode XID_Start character (such as a letter or underscore) followed by XID_Continue characters or digits; they are case-sensitive and normalized to Unicode Normalization Form C for equivalence.[55] Certain identifiers are reserved, including those starting with an underscore followed by an uppercase letter or containing double underscores, to avoid conflicts with implementation details.[56]
Preprocessor directives, starting with # and executed in translation phase 4, handle tasks like inclusion of headers (#include <iostream>) and macro definition (#define), with the directive itself being deleted after processing and any intervening whitespace becoming insignificant.[57] These directives form a separate phase before syntactic analysis, allowing conditional compilation and other preprocessing.
Since C++20, modules provide an alternative to the preprocessor for organizing and sharing code across translation units. A module is declared with export module ModuleName;, defining an interface that can be imported using import ModuleName; or import <header-unit>; for header units. Modules enable faster compilation by avoiding repeated parsing of headers and support stronger encapsulation, as exported names are explicitly controlled. Unlike includes, imports do not implicitly bring in macros or other preprocessor effects.[58]
Declarations introduce names into a program's scope and may or may not provide complete definitions; for instance, extern int x; declares x without allocating storage, while int x = 5; defines it with initialization.[59] Built-in types include fundamental ones like int for integers and bool for boolean values, which are integral types convertible to 0 (false) or 1 (true).[60] Functions are declared with a return type, name, and parameter list (e.g., int add(int a, int b);), and defined by adding a body (e.g., { return a + b; }), where the body specifies the function's behavior.[61]
Statements form the executable units of C++ programs, each typically ending with a semicolon, and control the flow of execution within blocks delimited by curly braces { }.[62] Control flow includes selection statements like if, which evaluates a condition contextually converted to bool and executes one substatement accordingly, optionally with an else clause; if constexpr allows compile-time evaluation for template contexts.[63] Iteration statements encompass while (condition checked before iteration), do-while (checked after), for (with optional initialization, condition, and increment), and range-based for for iterating over containers.[64] Jump statements such as break, continue, return, and goto alter control flow, with return exiting the function and optionally initializing the return value.[65]
Expressions compute values or produce side effects through operators and operands, with the language's grammar determining their structure.[66] Operator precedence and associativity dictate evaluation order; for example, multiplicative operators (*, /, %) have higher precedence than additive ones (+, -), and most binary operators associate left-to-right, as in a + b * c evaluating as a + (b * c).[67] The standard does not mandate a specific precedence table but implies it through the grammar, allowing implementations flexibility in regrouping associative operations while preserving semantics and avoiding undefined behavior like overflow.[68] Ambiguities between expressions and declarations are resolved syntactically, favoring declarations when possible.[69]
The C++ memory model classifies object storage into durations: automatic (block scope, lifetime ends at block exit), static (program lifetime, initialized once), thread-local (per-thread lifetime), and dynamic (runtime allocation via new, deallocation via delete).[70] Automatic storage is the default for local variables, destroyed in reverse order of construction upon scope exit.[71] Static storage uses the static keyword for globals or locals, ensuring initialization before main execution and persistence across function calls.[72] Dynamic allocation via new T invokes constructors and returns a pointer, throwing std::bad_alloc on failure unless std::nothrow is used; delete reverses this by calling destructors and freeing memory, with null pointers handled safely.[73]
Object-Oriented Programming
C++ provides robust support for object-oriented programming (OOP), enabling developers to model real-world entities through classes and objects while promoting code reusability and maintainability. Introduced in the original C++ standard, these features build on the language's C heritage by adding mechanisms for abstraction and modularity without sacrificing performance. Classes in C++ serve as blueprints for creating objects, combining data members and member functions within a single unit. A class declaration begins with the keywordclass followed by the class name and a body enclosed in braces, where access specifiers like public, private, and protected control visibility of members. By default, class members are private, enforcing data hiding from the outset. Member functions are methods that operate on the object's data, such as getters and setters, and can be defined inline or separately. Objects are instances of classes, created via constructors—special member functions automatically invoked upon object creation to initialize data members. For example, a constructor might take parameters to set initial values: ClassName::ClassName(int value) : member(value) {}. Destructors, named with a tilde prefix (e.g., ~ClassName()), handle cleanup when objects go out of scope or are explicitly deleted, ensuring resource management like memory deallocation. These constructors and destructors are crucial for the RAII (Resource Acquisition Is Initialization) idiom, where resources are acquired in constructors and released in destructors.[20]
Encapsulation in C++ is achieved primarily through access specifiers, which hide internal implementation details and expose only necessary interfaces. Private members are accessible only within the class, preventing direct external manipulation and reducing coupling between components. Protected members allow access from derived classes, supporting controlled extension. To grant selective access to private members without making them public, friend functions or classes can be declared inside the class using the friend keyword, such as friend void helperFunction(ClassName& obj);. This mechanism balances strict encapsulation with practical flexibility, though it should be used judiciously to avoid undermining data hiding principles.[20]
Inheritance allows a derived class to acquire members from a base class, promoting code reuse and hierarchical organization. C++ supports single inheritance, where a class derives from one base (e.g., class Derived : [public](/page/Public) Base {}), and multiple inheritance, permitting derivation from several bases (e.g., class Derived : [public](/page/Public) Base1, private Base2 {}). Multiple inheritance can lead to the diamond problem, resolved using virtual inheritance to ensure a single instance of a shared base class, declared as class Derived : virtual [public](/page/Public) Base {}. This avoids duplication and ambiguous member access. Overriding occurs when a derived class redefines a base class member function, requiring matching signatures; since C++11, the override keyword explicitly marks such functions to catch errors at compile time (e.g., void func() override;). Virtual base classes and overriding are essential for maintaining polymorphic behavior in inheritance hierarchies.[74][75]
Polymorphism in C++ enables objects of different classes to be treated uniformly through a common interface, primarily via virtual functions that support runtime binding. Declared with the virtual keyword in the base class (e.g., virtual void draw() = 0;), these functions allow derived classes to provide specific implementations, with the call resolved dynamically based on the object's actual type. Abstract classes, containing at least one pure virtual function (marked = 0), cannot be instantiated and serve as interfaces for derivation. Runtime Type Information (RTTI) complements this by providing mechanisms like typeid to query an object's type at runtime (e.g., typeid(*ptr).name()) and dynamic_cast for safe downcasting in polymorphic hierarchies (e.g., Derived* d = dynamic_cast<Derived*>(basePtr);). RTTI incurs a small runtime overhead but is invaluable for type-safe operations in dynamic contexts, enabled by default in most compilers unless explicitly disabled.[76][77]
Since C++23, explicit object member functions allow non-static member functions to have an explicit object parameter (deducing this), typically named self, as the first parameter. This enables template deduction on the object type, facilitating patterns like the Curiously Recurring Template Pattern (CRTP) without implicit this, e.g., template <typename Self> void func(this Self& self);. Such functions cannot be virtual, static, or have ref-qualifiers, but they enhance generic programming within OOP by allowing forwarding of the object parameter.[78]
Generic Programming and Templates
Generic programming in C++ is facilitated by templates, which enable the creation of reusable code that operates on multiple types while preserving type safety through compile-time checks. Introduced in the original C++ standard (ISO/IEC 14882:1998), templates allow programmers to define functions and classes parameterized by types or values, promoting abstraction without runtime overhead.[79] Function templates are declared using thetemplate keyword followed by a parameter list, such as template <typename T> T max(T a, T b) { return a > b ? a : b; }. When invoked, the compiler instantiates a specific function by substituting the actual type for T, for example, generating int max(int, int) for max(1, 2). Class templates follow a similar pattern, e.g., template <typename T> class Vector { T* data; size_t size; /* ... */ };, instantiated as Vector<int> to create a type-specific class with all members specialized accordingly. Instantiation occurs implicitly upon use or explicitly via template class Vector<double>;, ensuring the code is generated only when needed.[79]
Template specializations refine this mechanism by providing custom implementations for particular types or patterns. Full specialization replaces the entire template for a specific argument, as in template <> class Vector<bool> { /* bit-packed storage */ };, overriding the general case. Partial specialization applies to subsets, such as template <typename T> class Vector<T*> { /* pointer-optimized vector */ };, which matches when the type is a pointer. Variadic templates, added in C++11, extend this to arbitrary numbers of arguments using parameter packs, declared as template <typename... Types> struct [Tuple](/page/Tuple) { /* ... */ };. Pack expansion with ellipsis (...) allows unpacking, e.g., in void print(Types... args) { /* process each */ }, enabling flexible utilities like tuples or variadic functions.[79][80]
Template metaprogramming leverages templates for compile-time computations, treating them as a Turing-complete functional language executed during compilation. Techniques include recursive template specializations for algorithms like factorial: template <int N> struct Factorial { static const int value = N * Factorial<N-1>::value; }; template <> struct Factorial<0> { static const int value = 1; };, yielding Factorial<5>::value as 120 at compile time. SFINAE (Substitution Failure Is Not an Error), a key enabler, discards invalid template candidates during overload resolution if substitution fails, without diagnosing an error, as in enabling a function only for types with certain members. This supports type traits and conditional compilation, foundational to libraries like Boost.MPL.[81][82]
Concepts, introduced in C++20, refine template constraints by defining requirements on parameters, improving error messages and enabling better overload selection. A concept is declared as template <typename T> [concept](/page/Concept) EqualityComparable = requires(T a, T b) { {a == b} -> std::convertible_to<bool>; };, checking expressions at compile time. Templates can then require concepts, e.g., template <EqualityComparable T> void swap(T& a, T& b);, constraining T and providing diagnostics if unmet, such as "type lacks == operator" instead of deep instantiation errors. This builds on earlier proposals, subsuming SFINAE patterns for cleaner generic code.[83]
Concurrency and Parallelism
C++ introduced robust support for concurrency and parallelism with the C++11 standard, establishing a formal memory model to define the semantics of multi-threaded execution and prevent undefined behavior from data races. This model ensures that programs can reason about the ordering of memory accesses across threads, building on earlier single-threaded assumptions to accommodate modern multicore architectures. Prior to C++11, concurrency relied on platform-specific libraries, but the standard now mandates portable primitives for synchronization and atomicity, enabling developers to write thread-safe code without invoking undefined behavior.[84] Central to this support is the C++ memory model, which defines key relations like "sequenced-before" for operations within the same thread and "synchronizes-with" for inter-thread communication via atomic operations or locks. A data race occurs if two threads access the same non-atomic memory location concurrently, with at least one access being a write; such races result in undefined behavior, but the model guarantees sequential consistency for race-free programs unless weaker orderings are specified. This framework, formalized in the standard, draws from hardware realities like cache coherence while providing compiler guarantees for optimization. For instance, the relation ensures that if operation A synchronizes-with B, then A happens-before B, establishing a total order for visible side effects.[85][84] Atomic operations, provided by thestd::atomic template, allow lock-free access to shared variables with fine-grained control over memory ordering to balance performance and correctness. Common orderings include std::memory_order_seq_cst for sequential consistency, which imposes a global total order on all atomic operations, and relaxed orderings like std::memory_order_relaxed for independent counters where only atomicity is needed without synchronization. Operations such as fetch_add or compare_exchange_strong are indivisible, preventing intermediate states during concurrent modifications. This enables efficient implementations on hardware supporting instructions like compare-and-swap (CAS), reducing contention compared to mutex-based approaches.[84][86]
The std::thread class facilitates thread creation by wrapping a callable in a new execution thread, with constructors accepting functions and arguments for parameterized tasks. Since C++20, std::jthread extends this with automatic joining upon destruction, simplifying resource management: std::jthread t([]{ /* work */ });. To protect shared data, mutexes like std::mutex provide exclusive access via lock and unlock, while std::lock_guard offers RAII-based scoping to avoid deadlocks from forgotten unlocks. These primitives integrate with the memory model: unlocking a mutex synchronizes-with subsequent locks on the same mutex, ensuring visibility of prior writes. Threads can be joined to wait for completion or detached for fire-and-forget execution, supporting scalable parallel designs. C++20 also introduced cooperative cancellation via std::stop_source and std::stop_token, allowing threads to check for cancellation requests (e.g., if (token.stop_requested()) return;) and propagate stops, enabling graceful shutdowns without polling.[84][87]
Asynchronous programming is supported through futures and promises, where std::promise allows a thread to set a result or exception in a shared state, retrievable by std::future in another thread via get(). The std::async function simplifies this by launching a task asynchronously and returning a future, with policies to control deferred or immediate execution. This decouples producers and consumers, enabling non-blocking computations; for example, a background thread computes a value while the main thread proceeds, blocking only when the result is needed. Exceptions propagate through the future, maintaining error handling across threads.[84]
C++20 added synchronization primitives for coordinating threads: std::latch for one-time countdowns (e.g., waiting for N tasks to complete), std::barrier for repeated synchronization points among threads (with optional arrival notification), and std::semaphore for counting resources (binary or general). These complement mutexes for more efficient barrier-like patterns in parallel algorithms.[88]
C++17 extended parallelism to standard algorithms via execution policies in the <execution> header, allowing overloads of functions like std::for_each to run in parallel or vectorized modes. The policy std::execution::par enables multi-threaded execution for data-parallel tasks, distributing work across threads while preserving the algorithm's sequential semantics for deterministic results. std::execution::par_unseq further permits vectorization using SIMD instructions for finer-grained parallelism. These features leverage the underlying thread and atomic support, with implementations required to avoid data races internally; for example:
#include <execution>
#include <algorithm>
#include <vector>
std::vector<int> v = {1, 2, 3, 4, 5};
std::for_each(std::execution::par, v.begin(), v.end(), [](int& x) { x *= 2; });
#include <execution>
#include <algorithm>
#include <vector>
std::vector<int> v = {1, 2, 3, 4, 5};
std::for_each(std::execution::par, v.begin(), v.end(), [](int& x) { x *= 2; });
Standard Library
Containers and Iterators
The C++ standard library includes a collection of container classes designed to manage groups of objects efficiently, providing abstraction over underlying data structures while supporting common operations like insertion, removal, and access. These containers are templated to work with any type, enabling generic programming, and are defined in separate headers such as <vector>, <list>, <set>, and others. Containers are categorized into sequence, associative, and unordered associative types, each optimized for different access patterns and performance characteristics.[90] Sequence containers store elements in a linear arrangement, allowing efficient indexing by position and supporting operations such as push and pop at the ends. Thestd::vector class implements a dynamic array with contiguous storage, offering amortized constant-time insertion and deletion at the back via push_back and pop_back, while random access is O(1) due to its layout. In contrast, std::list uses a doubly-linked list for constant-time insertion and deletion at both ends with push_front, push_back, pop_front, and pop_back, though it lacks direct indexing and requires O(n) access by position. The std::deque container provides a double-ended queue with amortized constant-time operations at both ends, similar to vector but also supporting efficient insertion and deletion at the front. These containers form the foundation for linear data management in C++ programs.[91][92][93][90]
Associative containers maintain elements in a sorted order based on a comparison function, typically providing logarithmic time complexity for insertion, search, and deletion operations. The std::set class stores unique keys in a balanced binary search tree (often red-black), ensuring elements are ordered and allowing logarithmic-time lookups and insertions via methods like insert and find. Similarly, std::map associates unique keys with mapped values, also using a tree structure for O(log n) access, where keys determine the order and support efficient retrieval of values by key. These containers are ideal for scenarios requiring ordered storage without duplicates, with iterators traversing elements in sorted sequence.[94][95][90]
Unordered associative containers use hash tables for average constant-time operations, prioritizing speed over order. The std::unordered_set stores unique keys with an average O(1) insertion, deletion, and lookup via hashing, though worst-case performance degrades to O(n) due to collisions; it requires a hash function and equality comparable for keys. The std::unordered_map extends this to key-value pairs, enabling average O(1) access to values by hashed keys, with similar guarantees and requirements. These containers, introduced in C++11, offer high-performance alternatives when ordering is unnecessary.[96][97][90]
Iterators serve as generalized pointers to traverse and access elements within containers, providing a uniform mechanism for iterating over sequences regardless of the underlying structure. They are categorized by capability: input iterators support single-pass reading with incrementation; output iterators enable single-pass writing; forward iterators allow multi-pass traversal in one direction; bidirectional iterators add decrement for reverse movement; and random access iterators provide constant-time jumps and indexing. Each container supplies iterators matching its access efficiency, such as random access for vectors and bidirectional for lists. This categorization integrates seamlessly with the standard library by allowing algorithms to accept iterator pairs as input ranges, ensuring type-safe and performant operations across diverse containers.[98][99][100][90]
Algorithms and Utilities
The algorithms component of the C++ Standard Library, introduced as part of the Standard Template Library (STL) and formalized in the ISO/IEC 14882 standard, consists of generic functions that operate on iterator-defined ranges, promoting reusable and efficient sequence processing across container types.[101] These algorithms, declared primarily in the<algorithm> header, are divided into non-modifying operations that inspect ranges without alteration and modifying operations that transform elements or generate new sequences. Utilities complement these by providing type-safe helpers for common tasks, while numeric facilities support mathematical computations on arrays and specialized types. This design emphasizes genericity, allowing algorithms to work with diverse data structures via iterators.
Non-modifying algorithms enable inspection and querying of sequences without changing their contents, facilitating tasks like searching and counting. The std::find function scans a range for the first occurrence of a value, returning an iterator to it or the end iterator if absent; it supports customization via predicates for non-exact matches. For instance:
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> vec{1, 2, 3, 4, 5};
auto it = std::find(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
std::cout << "Found: " << *it << '\n';
}
}
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> vec{1, 2, 3, 4, 5};
auto it = std::find(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
std::cout << "Found: " << *it << '\n';
}
}
std::count tallies the number of elements equal to a given value, or matching a predicate, which is essential for statistical analysis on ranges. These operations leverage iterators for traversal, integrating seamlessly with container mechanisms.
Modifying algorithms alter sequences in place or produce transformed outputs, supporting data manipulation and reorganization. std::transform applies a unary function to each element in an input range, storing results in an output range, which is useful for mapping operations like scaling or conversion. An example includes doubling values:
#include <algorithm>
#include <vector>
#include <functional>
int main() {
std::vector<int> input{1, 2, 3};
std::vector<int> output(input.size());
std::transform(input.begin(), input.end(), output.begin(),
std::multiplies<int>{2});
// output now {2, 4, 6}
}
#include <algorithm>
#include <vector>
#include <functional>
int main() {
std::vector<int> input{1, 2, 3};
std::vector<int> output(input.size());
std::transform(input.begin(), input.end(), output.begin(),
std::multiplies<int>{2});
// output now {2, 4, 6}
}
std::copy transfers elements from a source range to a destination, preserving order and enabling efficient duplication or relocation. For reductions, std::accumulate from the <numeric> header folds a binary operation (defaulting to addition) over a range to compute aggregates like sums, with support for initial values and custom operators. Sorting falls here as a key modifying operation; std::sort rearranges elements in non-descending order using an optional strict weak ordering predicate for custom comparisons, such as sorting strings by length.
#include <algorithm>
#include <vector>
#include <string>
bool length_compare(const std::string& a, const std::string& b) {
return a.size() < b.size();
}
int main() {
std::vector<std::string> words{"apple", "a", "banana"};
std::sort(words.begin(), words.end(), length_compare);
// words now {"a", "apple", "banana"}
}
#include <algorithm>
#include <vector>
#include <string>
bool length_compare(const std::string& a, const std::string& b) {
return a.size() < b.size();
}
int main() {
std::vector<std::string> words{"apple", "a", "banana"};
std::sort(words.begin(), words.end(), length_compare);
// words now {"a", "apple", "banana"}
}
std::pair in <utility> combines two heterogeneous values into a single object, supporting structured returns from functions, while std::tuple generalizes this to arbitrary arity for more flexible grouping. Type traits in <type_traits>, such as std::is_integral, provide compile-time booleans to query type properties—like whether a type is an integer—enabling conditional compilation and metaprogramming. Smart pointers in <memory> automate resource management; std::unique_ptr exclusively owns a dynamically allocated object, deleting it upon destruction or reset, thus preventing leaks without shared ownership.
#include <memory>
#include <utility>
int main() {
auto up = std::make_unique<int>(42);
std::pair<std::unique_ptr<int>, int> p{std::move(up), 10};
// p.first owns the int; up is now null
}
#include <memory>
#include <utility>
int main() {
auto up = std::make_unique<int>(42);
std::pair<std::unique_ptr<int>, int> p{std::move(up), 10};
// p.first owns the int; up is now null
}
std::valarray in <valarray> models a dynamic array for element-wise operations, optimized for vectorized math like addition or trigonometric functions across the entire array, though it lacks the genericity of containers. For complex arithmetic, std::complex in <complex> encapsulates real and imaginary parts, overloading operators for addition, multiplication, and more, with specializations for floating-point types to ensure precision.
#include <complex>
#include <valarray>
#include <cmath>
int main() {
std::complex<double> z{1.0, 2.0};
std::complex<double> result = z * std::conj(z); // Magnitude squared
std::valarray<double> arr{1.0, 2.0, 3.0};
arr += std::sin(arr); // Element-wise sine and add
}
#include <complex>
#include <valarray>
#include <cmath>
int main() {
std::complex<double> z{1.0, 2.0};
std::complex<double> result = z * std::conj(z); // Magnitude squared
std::valarray<double> arr{1.0, 2.0, 3.0};
arr += std::sin(arr); // Element-wise sine and add
}
Input/Output and Strings
The input/output facilities in C++ are primarily provided through the<iostream> header, which defines a hierarchy of stream classes for handling data exchange between programs and external devices or files. At the core is the std::basic_ios class template, which serves as the base for input and output streams, managing formatting flags, error states, and locale associations. Derived from this are std::basic_istream for input operations like reading characters or formatted data, and std::basic_ostream for output operations such as writing to console or files. The bidirectional std::basic_iostream combines both, enabling streams to support reading and writing interchangeably. Standard objects include std::cin for console input from stdin, std::cout for console output to stdout, std::cerr for unbuffered error output to stderr, and std::clog for buffered error output, all of which are initialized upon inclusion of the header and flushed appropriately on program termination.[102]
For file-based input and output, the <fstream> header introduces std::basic_fstream, a class template that inherits from std::basic_iostream and associates with a std::basic_filebuf for buffered file operations. This class supports both reading and writing to files, with constructors allowing initialization by filename and open mode flags from std::ios_base, such as std::ios::in for reading, std::ios::out for writing, std::ios::app for appending, std::ios::binary for non-text mode, and std::ios::trunc to truncate the file on open (default for output). The open member function can also bind an existing file to the stream post-construction, while is_open checks the association status, enabling flexible file handling without unnecessary object creation. Wide-character variants like std::wfstream handle Unicode text.[103]
Stream formatting is controlled through manipulators and locales to ensure consistent and culturally appropriate output. Manipulators are functions or function objects inserted into streams via operator<< or operator>>, altering behavior for the next operation. For instance, std::setw(n) from <iomanip> sets the minimum field width to n characters for the subsequent input or output, padding with spaces if needed, while std::hex from <ios> switches integer output to hexadecimal base (lowercase letters), with std::dec and std::oct for decimal and octal respectively; these basefield flags persist until changed. Other manipulators include std::setfill for custom padding characters and std::setprecision for floating-point digits. Locales, defined in <locale>, encapsulate internationalization aspects like number formatting, date representation, and character classification, using facets—polymorphic classes such as std::num_put for numeric output and std::ctype for character traits. Streams are associated with a std::locale object, which can be imbued via std::basic_ios::imbue(loc) to apply locale-specific formatting, such as comma-separated thousands in European locales or right-to-left text support; the global locale is set with std::locale::global and defaults to the "C" locale for invariant behavior.[104][105][106]
String handling in the C++ standard library centers on std::basic_string from <string>, a contiguous sequence of characters that owns its data and supports dynamic resizing. Instantiated as std::string for char, it provides concatenation via operator+= (appending a string, character, or range) or the free operator+ for creating new strings, as in std::string result = str1 + str2;. Substring extraction uses substr(pos, len), returning a new std::string from position pos for up to len characters, throwing std::out_of_range if pos exceeds size. Additional operations include append for efficient range addition, find for locating substrings (returning std::string::npos on failure), replace for modifying portions, and compare for lexicographical ordering, all leveraging std::char_traits for character-specific behavior. Capacity management via reserve and capacity optimizes performance by preallocating memory.[107]
Introduced in C++17 via the <string_view> header, std::basic_string_view (typedef std::string_view for char) offers a lightweight, non-owning view of a contiguous character sequence, ideal for passing string data without copying or ownership transfer. It supports most std::string interfaces like substr, find, and compare, but lacks modification methods, ensuring the viewed data remains const; construction from literals, std::string, or arrays is efficient, as in std::string_view sv = "hello";. The view's lifetime must not exceed the underlying storage to avoid dangling references, and it integrates with ranges for iteration. This reduces overhead in functions accepting string arguments, promoting zero-copy semantics where possible.[108]
Pattern matching with strings is facilitated by the <regex> header since C++11, using std::basic_regex (typedef std::regex for char) to compile regular expressions according to grammars like ECMAScript (default) or POSIX variants. Constructors accept string patterns and flags such as std::regex::icase for case-insensitivity or std::regex::multiline (C++17) for line-based matching. Algorithms like std::regex_match check if the entire target sequence matches the regex, returning true only for full matches and optionally populating std::match_results with subexpressions, as in std::regex_match("abc123", rx, std::regex_constants::ECMAScript);. In contrast, std::regex_search finds the first partial match anywhere in the sequence, supporting iterator ranges, C-strings, or std::string inputs, with overloads for capturing groups. std::regex_replace enables substitution, enhancing text processing capabilities.[109][110]
Threading and Synchronization
The C++ standard library provides a comprehensive set of facilities for thread management and synchronization, introduced primarily in C++11 and extended in subsequent standards, to enable safe concurrent programming. These components, defined in headers such as<thread>, <mutex>, <condition_variable>, <future>, <atomic>, and <execution>, address the challenges of shared memory access and coordination among multiple threads.
Thread management in the standard library centers on the std::thread class, which represents a single thread of execution and launches concurrently upon construction by invoking a specified callable object. A std::thread object is move-constructible but not copyable, ensuring unique ownership, and provides methods to query its state, such as joinable() to check if it can be joined and get_id() for identification. To synchronize thread completion, join() blocks the calling thread until the managed thread finishes, transferring execution control, while detach() releases the thread to run independently, dissociating it from the object; failure to join or detach before destruction invokes std::terminate().[111]
Introduced in C++20, std::jthread extends std::thread with automatic joining upon destruction, eliminating the risk of termination from unjoined threads and simplifying resource management in scopes where explicit cleanup might be overlooked. It integrates cooperative cancellation via std::stop_token and std::stop_source, allowing threads to periodically check for stop requests and exit gracefully, which std::thread lacks natively. Like std::thread, std::jthread supports explicit join() and detach(), but its RAII-like behavior promotes safer usage in modern concurrent designs.[87]
Synchronization primitives ensure mutual exclusion and coordination, with std::mutex serving as the fundamental lock for protecting shared data from concurrent modification. This non-recursive, exclusive-ownership mutex employs lock() to block until acquisition and unlock() for release, or try_lock() for non-blocking attempts returning a boolean success indicator, preventing data races by serializing access. For more flexible locking, RAII wrappers like std::lock_guard and std::unique_lock manage mutex lifetime automatically, supporting exception safety and deferred unlocking.[112][113][114]
std::condition_variable, used exclusively with std::unique_lock<std::mutex>, enables threads to wait for specific conditions while releasing the associated mutex, then reacquire it upon notification to avoid busy-waiting. Waiting threads invoke wait(), wait_for(), or wait_until() to suspend until notified via notify_one() or notify_all() from another thread, which must hold the mutex during condition changes; spurious wakeups necessitate rechecking the condition predicate. This pair facilitates producer-consumer patterns and other event-driven synchronization without polling overhead.[115]
Asynchronous operations and result synchronization are handled by std::future, which accesses the shared state of deferred computations initiated via std::async(), std::packaged_task, or std::promise. A std::future object blocks on get() to retrieve the result (moving it from the shared state) or uses wait() variants for timed synchronization, propagating exceptions if the operation fails; once consumed, the future becomes invalid. This mechanism decouples task launching from result retrieval, supporting fire-and-forget parallelism while ensuring thread-safe value passing.[116]
Lock-free synchronization relies on std::atomic, a template specializing fundamental types for atomic operations that guarantee indivisible execution across threads, avoiding locks for performance-critical shared variables. Key operations include load() to atomically read the value under a specified memory order, store() to replace it atomically, and compare_exchange_weak() or compare_exchange_strong() to conditionally exchange if matching an expected value, enabling lock-free algorithms like compare-and-swap (CAS). Memory ordering parameters, such as std::memory_order_seq_cst for sequential consistency, control visibility and ordering guarantees.[117][118]
C++17 introduced execution policies in the <execution> header to parallelize standard library algorithms without explicit thread management, specifying how operations like std::for_each or std::sort execute. The std::execution::par policy permits concurrent thread-based parallelism for throughput-oriented tasks, while std::execution::par_unseq additionally allows vectorization and unsequenced operations for SIMD exploitation, potentially yielding higher performance on multi-core hardware; std::execution::seq enforces sequential execution as the default. These policies integrate with the STL to leverage concurrency transparently, provided the algorithm and data structures are thread-safe.[119][120][121]
Compatibility and Interoperability
With C Language
C++ was designed to maintain a high degree of backward compatibility with C, allowing much of the existing C codebase to be compiled and used within C++ programs with minimal modifications. A significant portion of valid C code constitutes a subset of C++, meaning it can be compiled by a C++ compiler, though certain adjustments may be required for constructs that differ between the languages, such as the lack of implicit conversions fromvoid* to other pointer types in C++—unlike in C, where such conversions are automatic—necessitating explicit casts like static_cast<T*>(ptr). This compatibility stems from C++'s origins as an extension of C, ensuring that C libraries and applications could be incrementally upgraded or integrated without complete rewrites.[122]
At the linking level, object files produced by C and C++ compilers are generally interchangeable, provided they adhere to the same application binary interface (ABI) and are generated by compatible compiler versions from the same vendor. This enables mixed-language projects where C modules can be linked into C++ executables, and vice versa, without significant overhead, as C++ supports calling C functions directly when properly declared. However, C++'s support for function overloading and namespaces introduces name mangling, where compiler-generated symbol names are altered (e.g., appending type information) to distinguish overloaded functions, potentially causing linkage failures with unmangled C symbols. To resolve this, the extern "C" linkage specification is used, which instructs the C++ compiler to avoid name mangling and employ C calling conventions for specified functions or blocks, as in extern "C" { void func(int); }. This mechanism allows seamless interoperability, such as wrapping C++ functions for use in C code or including C headers in C++ with conditional extern "C" guards.[123][122]
Despite these compatibilities, C++ imposes stricter type rules than C, which can require adjustments to legacy code. For instance, C++ eliminates implicit int declarations (removed in C99 but present in earlier C standards) and enforces more rigorous type checking, disallowing certain implicit conversions that C permits, such as function pointer mismatches without casts. Other limitations include C++'s reserved keywords (e.g., class, new) that cannot be used as identifiers in C++ but might be in C, necessitating renames, and the absence of some C99 features like variable-length arrays in early C++ standards. Historically, tools like cfront, the original C++ compiler developed by Bjarne Stroustrup, facilitated transitions by translating C++ code to C, allowing compilation with C compilers and aiding the porting of C codebases during C++'s early adoption in the 1980s and 1990s.[122]
Inline Assembly Integration
Inline assembly allows developers to embed low-level machine instructions directly within C++ code, enabling fine-grained control over hardware for performance-critical operations. This integration is primarily supported through compiler-specific extensions, as the C++ standard does not define inline assembly semantics. In GCC and compatible compilers like Clang, the basic form uses theasm keyword (or __asm__ for strict ANSI compliance) to insert simple assembly statements, such as asm("nop"); for a no-operation instruction. The extended form provides more sophisticated integration by specifying inputs, outputs, and clobbers, formatted as asm [volatile] ("template" : output_operands : input_operands : clobbers);. Here, the template is a string containing assembly instructions with placeholders (e.g., %0 for the first output), output_operands map C++ variables to assembly destinations using constraints like "=r" for a general register, input_operands supply values from C++ expressions via constraints like "r" for registers, and clobbers list modified resources such as registers (e.g., "cc" for flags) or memory (e.g., "memory") to inform the compiler of side effects.[124]
In Microsoft Visual C++ (MSVC), inline assembly employs __asm blocks, as in __asm { mov eax, ebx; }, which embed instructions directly without the extended operand syntax of GCC; this is limited to x86/x64 architectures and unsupported on ARM or in 64-bit mode for certain features. Common use cases include hardware-specific optimizations, such as reading the time-stamp counter with asm volatile ("rdtsc" : "=A" (val)); on x86 to measure cycles precisely, and leveraging SIMD instructions for vectorized computations. For instance, inline assembly can invoke SIMD operations like SSE or AVX on x86 for parallel data processing in loops, or SVE on Arm for scalable vector extensions, where intrinsics might not suffice for custom alignments or interleaving. These applications are typical in embedded systems, graphics rendering, or numerical simulations requiring direct access to vector registers unavailable through higher-level abstractions.[125][124][126]
Portability challenges arise from these compiler- and architecture-specific extensions; GCC's AT&T syntax differs from MSVC's Intel syntax, and code targeting x86 SIMD will not compile on Arm without rewrites, often necessitating conditional compilation via preprocessor directives like #ifdef __GNUC__. Safety concerns are paramount, as improper use can introduce undefined behavior, such as unlisted memory clobbers leading to optimizer errors or race conditions in multithreaded code. To mitigate this, developers must declare all modified resources in clobbers (e.g., "memory" for volatile accesses) and use volatile qualifiers to prevent reordering, ensuring compatibility with C++'s abstract machine model. Integration with C++ objects requires careful handling, like using lvalues for outputs to avoid temporaries, and recent proposals extend the memory model to formally account for inline assembly's effects on visibility and ordering. Inline assembly can interface with C-compatible code, but its low-level nature demands rigorous testing to avoid subtle bugs.[124][125][127]
Cross-Language and Cross-Platform Considerations
C++ facilitates interoperability with other programming languages primarily through foreign function interfaces (FFIs), which allow C++ code to call or be called by functions written in languages like Python or Java. For Python integration, the pybind11 library provides a lightweight, header-only mechanism to expose C++ classes, functions, and data structures as Python modules, enabling seamless binding without requiring extensive boilerplate code. This approach leverages Python's C API under the hood, ensuring high-performance interactions suitable for numerical computing or machine learning applications where C++ handles performance-critical components. Similarly, the Java Native Interface (JNI) serves as the standard framework for invoking C++ code from Java programs running on the Java Virtual Machine (JVM), permitting native methods to access Java objects and vice versa while managing memory across the language boundary.[128] JNI requires explicit handling of data types and exceptions to maintain type safety, and it is commonly used in Android development for performance-sensitive tasks like graphics rendering. In cases where direct bindings are impractical due to C++'s non-standardized application binary interface (ABI), interoperability often routes through the more stable C ABI by declaring functions withextern "C", which unmangles names and adheres to C calling conventions, allowing C++ libraries to interface with languages like Rust or Go via shared libraries.[129]
Achieving cross-platform portability in C++ relies on adherence to the ISO C++ standard, which defines language features independent of underlying operating systems, thereby enabling code to compile and run on diverse environments such as Unix-like systems (e.g., Linux, macOS) and Windows without modification.[130] Compiler vendors like GCC, Clang, and Microsoft Visual C++ (MSVC) implement this standard to varying degrees of completeness, with the Universal C Runtime (UCRT) on Windows providing conformance to C99 requirements essential for C++ standard library functionality. To handle platform-specific differences—such as file paths, threading models, or socket APIs—developers employ conditional compilation directives like #ifdef or #if defined, which selectively include code blocks based on predefined macros (e.g., _WIN32 for Windows or __unix__ for Unix systems).[131] This technique minimizes runtime checks and maintains a single codebase, though overuse can lead to maintenance challenges in large projects; best practices recommend abstracting platform variances behind interfaces or using cross-platform libraries like Boost.
ABI stability poses significant challenges for binary compatibility in C++, particularly across compilers and versions, as the language lacks a universal ABI specification, leading to differences in how object layouts, function calling conventions, and exception handling are implemented. The Itanium C++ ABI, adopted by GCC and Clang, defines rules for name mangling, virtual table layouts, and template instantiations to promote interoperability on Unix-like platforms, but it diverges from the Microsoft Visual C++ (MSVC) ABI used on Windows, which employs distinct conventions for member function pointers and exception unwinding.[129][132] These variances can cause linking failures or runtime crashes when mixing object files from different compilers. Templates exacerbate ABI issues because they are compiled inline, meaning changes to template parameters or compiler optimizations can alter binary representations without source-level warnings, often requiring recompilation of dependent code to ensure compatibility.[133] To mitigate this, developers freeze ABI-critical interfaces (e.g., public classes without virtual changes) and use tools like ABI checkers, but full stability across ecosystems remains elusive without restricting features like inlining or exceptions.
Tools like CMake address cross-platform build challenges by generating native makefiles or project files for multiple operating systems and compilers from a platform-agnostic CMakeLists.txt configuration, facilitating reproducible builds on Unix, Windows, and even embedded systems.[134] CMake supports conditional logic via its own if() constructs to select libraries or flags (e.g., POSIX threads on Unix vs. Win32 threads on Windows), and it integrates with package managers like vcpkg or Conan to resolve dependencies while preserving binary compatibility where possible. By abstracting toolchain specifics, CMake ensures that C++ projects maintain portability without embedding excessive #ifdef directives directly in source code, though ABI mismatches still necessitate separate builds per compiler family.
Implementations and Ecosystem
Compilers and Toolchains
C++ compilers translate source code into machine-executable binaries, supporting the language's evolving standards while incorporating platform-specific optimizations and extensions. Major implementations include the GNU Compiler Collection (GCC), Clang with the LLVM backend, and Microsoft Visual C++ (MSVC), each offering distinct features for development efficiency and compliance.[135][136][137] GCC, developed by the Free Software Foundation, is an open-source compiler suite that provides comprehensive support for C++ standards up to C++23, with experimental features available since GCC 11 and improved experimental support in GCC 15 (released 2025). It enables C++23 mode via the-std=c++23 flag and includes GNU extensions such as enhanced concepts diagnostics beyond the standard, aiding template metaprogramming. Widely used in Linux environments, GCC integrates with the GNU Binutils for linking and assembly, ensuring robust cross-platform compilation.[135][138]
Clang, part of the LLVM project, emphasizes modularity and rapid compilation times through its frontend-backend separation, allowing interchangeable optimizations and diagnostics. As of 2025, Clang offers partial C++23 support with over 30 features implemented, such as deducing this parameters and multidimensional subscript operators, activated by -std=c++23. Its integrated static analysis tools, like Clang Static Analyzer, detect issues such as null pointer dereferences at compile time, enhancing code reliability without runtime overhead. LLVM's infrastructure also supports just-in-time compilation for dynamic scenarios.[136][136]
MSVC, Microsoft's proprietary compiler, is optimized for Windows development, providing seamless integration with the Windows API and strong debugging capabilities through features like std::source_location for precise error tracking. In November 2025, it achieves partial C++23 conformance, supporting core features such as deducing this (P0847R7) while lacking others like extended floating-point types, as detailed in Visual Studio 2022 version 17.13 updates. Its Edit and Continue functionality allows incremental code changes during debugging sessions, reducing iteration times for Windows-native applications.[137][137]
Supporting these compilers are toolchains for building and debugging C++ projects. GNU Make automates compilation by processing makefiles that define dependencies and rules, such as invoking g++ to compile .cpp files into executables, ensuring only modified sources are rebuilt for efficiency.[139] CMake, a cross-platform meta-build system, generates native build files for tools like Make or MSBuild, abstracting platform differences to simplify multi-compiler workflows, such as configuring include paths and linking libraries declaratively.[140]
For debugging, the GNU Debugger (GDB) enables runtime inspection of C++ programs, supporting breakpoints, variable watches, and stack traces across UNIX-like systems, with version 16.3 in 2025 adding enhancements for multi-threaded execution. LLDB, LLVM's debugger, offers similar capabilities with superior performance on macOS and Linux, leveraging Clang's parser for accurate expression evaluation in C++ contexts like template instantiations.[141][142]
Integrated Development Environments
Integrated development environments (IDEs) for C++ provide comprehensive tools that integrate editing, building, debugging, and analysis within a single interface, enhancing productivity for developers working on complex projects. These tools often leverage language servers and extensions to offer features like code completion, refactoring, and error detection tailored to C++'s syntax and standards. Popular IDEs vary from full-featured graphical environments to lightweight editors extensible via plugins, supporting cross-platform development across Windows, Linux, and macOS. Microsoft Visual Studio stands out as a full-featured IDE primarily optimized for Windows-based C++ development, offering robust support for desktop applications, Universal Windows apps, and cross-platform targets like Linux. It includes IntelliSense for intelligent code completion, symbol navigation, and visualization tools such as syntax colorization, code tooltips, Class View, and Call Hierarchy to aid in understanding large codebases.[143] The IDE excels in debugging capabilities, allowing breakpoints, variable inspection, performance profiling, and real-time remote debugging for Linux applications using GDB, which facilitates troubleshooting multi-threaded and distributed systems without local deployment.[143] CLion, developed by JetBrains, is a cross-platform IDE specifically designed for C and C++ programming, supporting native development on Windows, Linux, and macOS with seamless integration for build systems like CMake. Its smart editor provides on-the-fly code analysis, including data flow analysis (DFA) to detect potential errors and warnings with quick-fix suggestions, alongside powerful coding assistance for efficient workflow.[144] CLion's refactoring tools enable reliable code transformations, such as extracting methods, renaming symbols, and generating boilerplate like getters, setters, and templates, while its debugger offers advanced investigation features like inline variable values and multi-session support.[144] Visual Studio Code (VS Code) serves as a lightweight, extensible code editor that transforms into a capable C++ IDE through official extensions, making it suitable for cross-platform development on Windows, Linux, and macOS. The Microsoft C/C++ extension delivers IntelliSense for syntax highlighting, smart completions, error checking, and hovers, relying on command-line compilers like GCC or Clang for building.[145] Complementary tools like CMake Tools enable project configuration and build management, while integrated debugging supports configurable launchers for stepping through code and inspecting variables.[145] For developers preferring text-based editors, Emacs can be configured as a sophisticated C++ IDE using packages like lsp-mode, which integrates language servers such as clangd for semantic completion, error checking, and navigation.[146] Plugins including flycheck provide real-time syntax highlighting and linting, company-mode handles autocompletion, and dap-mode enables debugging with GDB integration, all hooked into C++ modes for automated setup.[146] Similarly, Vim and its fork Neovim support C++ development through plugins like coc.nvim, which hosts language servers such as clangd for features including code completion, diagnostics, and refactoring via a configuration file.[147] This setup includes built-in syntax highlighting and can incorporate build tools through tasks or external plugins, allowing customization for efficient editing in terminal environments.[147]Performance and Optimization Techniques
C++ enables high-performance computing through a combination of compiler optimizations, profiling tools, and language-specific techniques that leverage hardware capabilities. These methods allow developers to minimize execution time, reduce memory usage, and exploit modern processor architectures effectively. By applying these optimizations judiciously, C++ programs can achieve near-native hardware speeds, making it a preferred choice for systems programming, game engines, and scientific simulations.[148] Compiler optimizations play a foundational role in enhancing C++ performance without altering source code. Flags such as -O1, -O2, and -O3 in GCC and Clang control levels of optimization, where -O2 enables aggressive transformations like function inlining and dead code elimination, often yielding 10-20% speedups over unoptimized builds (-O0). Inline functions, marked with the inline keyword or via attributes, reduce function call overhead by embedding the function body at the call site, which is particularly beneficial for small, frequently invoked routines; for instance, inlining a simple accessor method can eliminate the cost of parameter passing and return jumps. Loop unrolling, automatically applied at higher optimization levels like -O3, duplicates loop iterations to reduce branch overhead and improve instruction-level parallelism, though it increases code size and may pressure the instruction cache if over-applied.[148][148][148] Profiling tools are essential for identifying performance bottlenecks in C++ applications. The Linux perf tool, part of the kernel's performance analysis suite, samples CPU events like cache misses and branch predictions to pinpoint hot code paths, enabling developers to focus optimizations where they matter most; for example, perf record followed by perf report can reveal that a loop is stalling due to data dependencies. Valgrind's Callgrind simulates execution to profile instruction counts and memory accesses, helping detect inefficiencies such as excessive allocations; in one case study, it identified a bottleneck in a sorting algorithm where repeated memory reallocations doubled runtime. These tools provide instrumentation-free insights, contrasting with invasive debuggers, and support iterative refinement.[149][150][150] Move semantics, introduced in C++11, optimize resource management by transferring ownership of objects rather than copying them, significantly reducing overhead in containers and algorithms. For rvalue references (e.g., std::move), this avoids deep copies of large data structures like vectors, potentially cutting construction time by up to 70% in operations involving temporary objects, as demonstrated in benchmarks of string concatenations and vector resizes. A representative example is:std::vector<std::string> v;
v.emplace_back("hello"); // Constructs in place
std::string temp = "world";
v.push_back(std::move(temp)); // Moves, leaving temp empty
std::vector<std::string> v;
v.emplace_back("hello"); // Constructs in place
std::string temp = "world";
v.push_back(std::move(temp)); // Moves, leaving temp empty
#include <immintrin.h>
__m256 a = _mm256_load_ps([data](/page/Data));
__m256 b = _mm256_load_ps([data](/page/Data) + 8);
__m256 result = _mm256_add_ps(a, b);
_mm256_store_ps(output, result);
#include <immintrin.h>
__m256 a = _mm256_load_ps([data](/page/Data));
__m256 b = _mm256_load_ps([data](/page/Data) + 8);
__m256 result = _mm256_add_ps(a, b);
_mm256_store_ps(output, result);
Community and Applications
Usage in Industry and Research
C++ is extensively utilized in industry for developing high-performance software in domains requiring low-latency execution, resource efficiency, and robust systems integration. Its adoption stems from the language's ability to provide fine-grained control over hardware resources while supporting object-oriented and generic programming paradigms, making it ideal for applications where performance bottlenecks cannot be tolerated. As of 2025, C++ ranks among the top programming languages in popularity indices, reflecting its enduring relevance in performance-critical sectors.[157] In the gaming industry, C++ powers major game engines, enabling complex real-time rendering, physics simulations, and multiplayer networking. For instance, Unreal Engine, developed by Epic Games, is primarily written in C++, allowing developers to create high-fidelity 3D environments and experiences across platforms like consoles, PCs, and mobile devices.[158] Similarly, web browsers such as Google Chrome rely heavily on C++ for their core rendering engines and JavaScript interpreters; the V8 engine, which powers JavaScript execution in Chrome, is implemented in C++ to achieve high-speed performance for dynamic web applications.[159] The financial sector, particularly high-frequency trading (HFT), leverages C++ for its capacity to handle ultra-low-latency operations and concurrent data processing. HFT firms use C++ to develop trading algorithms that execute millions of transactions per second, optimizing for minimal overhead in network I/O and algorithmic computations; design patterns tailored for low-latency applications, such as lock-free data structures, are commonly implemented in C++ for this purpose.[160] In systems programming, C++ contributes to operating system components, including user-mode subsystems and kernel-mode drivers, where it supports hardware abstraction layers.[161] The kernel core remains in C. In the automotive industry, C++ is prevalent in embedded systems for engine control units (ECUs) and advanced driver-assistance systems (ADAS), adhering to safety standards like AUTOSAR C++14 guidelines to ensure reliability in safety-critical environments.[162][163] In research, C++ plays a pivotal role in high-performance computing (HPC) and scientific simulations, where its efficiency enables processing vast datasets on supercomputers. At CERN, C++ frameworks underpin particle physics simulations, such as Monte Carlo event generators in the ROOT system, facilitating the analysis of high-energy collision data from the Large Hadron Collider.[164] In artificial intelligence, C++ forms the backend of major machine learning libraries; TensorFlow's core operations, including tensor computations and neural network execution, are implemented in C++ for optimized performance across CPU, GPU, and TPU hardware.[165] Overall, C++'s dominance in these areas is evidenced by its use among millions of developers globally, with surveys indicating it is used by about 22% of developers, particularly in embedded, systems, and computational fields.[166]Learning Resources and Best Practices
Learning C++ effectively requires a combination of authoritative texts, online references, and structured educational platforms. Bjarne Stroustrup's "The C++ Programming Language" (fourth edition) serves as the definitive reference, detailing the language's features, standard library, and design principles directly from its creator.[167] For beginners, Stroustrup's "Programming: Principles and Practice Using C++" (second edition) introduces core concepts through practical examples and exercises, emphasizing problem-solving and good habits.[167] Scott Meyers' "Effective C++" (third edition) provides 55 targeted items to enhance code quality, resource management, and object-oriented design, making it indispensable for intermediate learners transitioning to robust programming. Online resources complement these books by offering quick access to syntax and examples. Cppreference.com is a comprehensive, community-maintained reference covering C++ standards from C++98 through C++23, including language elements, standard library components, and compiler support tables.[168] The official ISO/IEC 14882 standards, such as the 2020 edition for C++20, define the language's precise requirements and are essential for in-depth study, available for purchase from the International Organization for Standardization.[169] Interactive courses on platforms like Coursera and edX provide guided instruction; for instance, the "Coding for Everyone: C and C++" specialization on Coursera covers fundamentals to advanced topics like object-oriented programming and data structures through hands-on projects.[170] Similarly, edX's "C++ Programming Essentials" professional certificate from IBM includes modules on syntax, object-oriented implementation, and algorithms with practical coding exercises.[171] Adopting best practices is crucial for writing safe, maintainable C++ code. Resource Acquisition Is Initialization (RAII) ties resource management—such as memory, files, or locks—to object lifetimes, ensuring automatic cleanup via destructors and preventing leaks even on exceptions.[19] Const-correctness involves declaring objects, parameters, and return types asconst wherever modifications are not intended, which enforces immutability, aids compiler error detection, and supports optimizations like inlining.[19] To avoid common pitfalls, modern C++ discourages raw pointers for ownership, recommending smart pointers like std::unique_ptr for exclusive ownership and std::shared_ptr for shared ownership, which automate deletion and reduce dangling pointer risks.[19]
The C++ Core Guidelines, developed by the ISO C++ committee and led by Bjarne Stroustrup and Herb Sutter, offer a comprehensive set of rules for modern C++ (post-C++11), spanning 400+ items on interfaces, resource management, expressions, classes, concurrency, and error handling to promote readable, efficient, and error-resistant code.[19] These guidelines emphasize leveraging C++11 and later features like auto, lambdas, move semantics, and ranges to simplify code while maintaining performance, and they include enforcement recommendations via tools like static analyzers.[19]