// Example from C++11 Wiki web page: // C++ has always had the concept of constant expressions. These are expressions such as 3+4 that will // always yield the same results, at compile time and at run time. Constant expressions are optimization // opportunities for compilers, and compilers frequently execute them at compile time and hardcode the // results in the program. Also, there are a number of places where the C++ specification requires the // use of constant expressions. Defining an array requires a constant expression, and enumerator values // must be constant expressions. // However, constant expressions have always ended whenever a function call or object constructor was // encountered. So a piece of code as simple as this is illegal: int get_five() {return 5;} int some_value[get_five() + 7]; // Create an array of 12 integers. Ill-formed C++ // This was not legal in C++03, because get_five() + 7 is not a constant expression. A C++03 compiler // has no way of knowing if get_five() actually is constant at runtime. In theory, this function could // affect a global variable, call other non-runtime constant functions, etc. // C++11 introduced the keyword constexpr, which allows the user to guarantee that a function or object // constructor is a compile-time constant [8]. The above example can be rewritten as follows: constexpr int get_five() {return 5;} int some_value[get_five() + 7]; // Create an array of 12 integers. Legal C++11 // This allows the compiler to understand, and verify, that get_five is a compile-time constant. // The use of constexpr on a function imposes some limitations on what that function can do. First, the // function must have a non-void return type. Second, the function body cannot declare variables or define // new types. Third, the body may contain only declarations, null statements and a single return statement.
// Core language runtime performance enhancements // Rvalue references and move constructors class A { A& operator=(A&& rhs) { } }; // Generalized constant expressions // GCC 4.6 constexpr int get_five() {return 5;} int some_value[get_five() + 7]; constexpr double acceleration_due_to_gravity = 9.8; constexpr double moon_gravity = acceleration_due_to_gravity / 6.0; // Modification to the definition of plain old data // Core language build time performance enhancements // Extern template template<class T> class B { }; extern template class B<int>; // Core language usability enhancements // Initializer lists