C++11
C++11 is a version of a joint technical standard, ISO/IEC 14882, by the International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC), for the C++ programming language. C++11 replaced the prior version of the C++ standard, named C++03,[1] and was later replaced by C++14. The name follows the tradition of naming language versions by the publication year of the specification, though it was formerly named C++0x because it was expected to be published before 2010.[2] Although one of the design goals was to prefer changes to the libraries over changes to the core language,[3] C++11 does make several additions to the core language. Areas of the core language that were significantly improved include multithreading support, generic programming support, uniform initialization, and performance. Significant changes were also made to the C++ Standard Library, incorporating most of the C++ Technical Report 1 (TR1) libraries, except the library of mathematical special functions.[4] C++11 was published as ISO/IEC 14882:2011[5] in September 2011 and is available for a fee. The working draft most similar to the published C++11 standard is N3337, dated 16 January 2012;[6] it has only editorial corrections from the C++11 standard.[7] C++11 was fully supported by Clang 3.3 and later,[8] and by GNU Compiler Collection (GCC) 4.8.1 and later.[9] Design goalsThe design committee attempted to stick to a number of goals in designing C++11:
Attention to beginners is considered important, because most computer programmers will always be such, and because many beginners never widen their knowledge, limiting themselves to work in aspects of the language in which they specialize.[2][3] Extensions to the C++ core languageOne function of the C++ committee is the development of the language core. Areas of the core language that were significantly improved include multithreading support, generic programming support, uniform initialization, and performance. Core language runtime performance enhancementsThese language features primarily exist to provide some kind of runtime performance benefit, either of memory or of computing speed.[citation needed] Rvalue references and move constructorsIn C++03 (and before), temporaries (termed "rvalues", as they often lie on the right side of an assignment) were intended to never be modifiable — just as in C — and were considered to be indistinguishable from A chronic performance problem with C++03 is the costly and unneeded deep copies that can happen implicitly when objects are passed by value. To illustrate the issue, consider that an In C++11, a move constructor of Rvalue references can provide performance benefits to existing code without needing to make any changes outside the standard library. The type of the returned value of a function returning an For safety reasons, some restrictions are imposed. A named variable will never be considered to be an rvalue even if it is declared as such. To get an rvalue, the function template Due to the nature of the wording of rvalue references, and to some modification to the wording for lvalue references (regular references), rvalue references allow developers to provide perfect function forwarding. When combined with variadic templates, this ability allows for function templates that can perfectly forward arguments to another function that takes those particular arguments. This is most useful for forwarding constructor parameters, to create factory functions that will automatically call the correct constructor for those particular arguments. This is seen in the emplace_back set of the C++ standard library methods. constexpr – Generalized constant expressionsC++ has always had the concept of constant expressions. These are expressions such as However, a constant expression has never been allowed to contain a function call or object constructor. So a piece of code as simple as this is invalid: int getFive() {
return 5;
}
int someValue[getFive() + 7]; // Create an array of 12 integers. Ill-formed C++
This was not valid in C++03, because C++11 introduced the keyword constexpr int getFive() {
return 5;
}
int someValue[getFive() + 7]; // Create an array of 12 integers. Valid C++11
This allows the compiler to understand, and verify, that Using Before C++11, the values of variables could be used in constant expressions only if the variables are declared const, have an initializer which is a constant expression, and are of integral or enumeration type. C++11 removes the restriction that the variables must be of integral or enumeration type if they are defined with the constexpr double earthGravitationalAcceleration = 9.8;
constexpr double moonGravitationalAcceleration = earthGravitationalAcceleration / 6.0;
Such data variables are implicitly const, and must have an initializer which must be a constant expression. To construct constant expression data values from user-defined types, constructors can also be declared with The copy constructor for a type with any If a constexpr function or constructor is called with arguments which aren't constant expressions, the call behaves as if the function were not constexpr, and the resulting value is not a constant expression. Likewise, if the expression in the return statement of a constexpr function does not evaluate to a constant expression for a given invocation, the result is not a constant expression.
Modification to the definition of plain old dataIn C++03, a class or struct must follow a number of rules for it to be considered a plain old data (POD) type. Types that fit this definition produce object layouts that are compatible with C, and they could also be initialized statically. The C++03 standard has restrictions on what types are compatible with C or can be statically initialized despite there being no technical reason a compiler couldn't accept the program; if someone were to create a C++03 POD type and add a non-virtual member function, this type would no longer be a POD type, could not be statically initialized, and would be incompatible with C despite no change to the memory layout. C++11 relaxed several of the POD rules, by dividing the POD concept into two separate concepts: trivial and standard-layout. A type that is trivial can be statically initialized. It also means that it is valid to copy data around via A trivial class or struct is defined as one that:
Constructors are trivial only if there are no virtual member functions of the class and no virtual base classes. Copy/move operations also require all non-static data members to be trivial. A type that is standard-layout means that it orders and packs its members in a way that is compatible with C. A class or struct is standard-layout, by definition, provided:
A class/struct/union is considered POD if it is trivial, standard-layout, and all of its non-static data members and base classes are PODs. By separating these concepts, it becomes possible to give up one without losing the other. A class with complex move and copy constructors may not be trivial, but it could be standard-layout and thus interoperate with C. Similarly, a class with public and private non-static data members would not be standard-layout, but it could be trivial and thus Core language build-time performance enhancementsExtern templateIn C++03, the compiler must instantiate a template whenever a fully specified template is encountered in a translation unit. If the template is instantiated with the same types in many translation units, this can dramatically increase compile times. There is no way to prevent this in C++03, so C++11 introduced extern template declarations, analogous to extern data declarations. C++03 has this syntax to oblige the compiler to instantiate a template: template class std::vector<MyClass>;
C++11 now provides this syntax: extern template class std::vector<MyClass>;
which tells the compiler not to instantiate the template in this translation unit. Core language usability enhancementsThese features exist for the primary purpose of making the language easier to use. These can improve type safety, minimize code repetition, make erroneous code less likely, etc. Initializer listsC++03 inherited the initializer-list feature from C. A struct or array is given a list of arguments in braces, in the order of the members' definitions in the struct. These initializer-lists are recursive, so an array of structs or struct containing other structs can use them. struct FloatAndInt {
float first;
int second;
};
FloatAndInt scalar = {0.43f, 10}; // One Object, with first=0.43f and second=10
FloatAndInt anArray[] = {{13.4f, 3}, {43.28f, 29}, {5.934f, 17}}; // An array of three Objects
This is very useful for static lists, or initializing a struct to some value. C++ also provides constructors to initialize an object, but they are often not as convenient as the initializer list. However, C++03 allows initializer-lists only on structs and classes that conform to the Plain Old Data (POD) definition; C++11 extends initializer-lists, so they can be used for all classes including standard containers like C++11 binds the concept to a template, called class SequenceClass {
public:
SequenceClass(std::initializer_list<int> list);
};
This allows SequenceClass someSeq = {1, 4, 5, 6};
This constructor is a special kind of constructor, called an initializer-list-constructor. Classes with such a constructor are treated specially during uniform initialization (see below) The template class The list can be copied once constructed, which is cheap and will act as a copy-by-reference (the class is typically implemented as a pair of begin/end pointers). An Although its construction is specially treated by the compiler, an void functionName(std::initializer_list<float> list); // Copying is cheap; see above
functionName({1.0f, -3.45f, -0.4f});
Examples of this in the standard library include the Standard containers can also be initialized in these ways: std::vector<std::string> v = { "xyzzy", "plugh", "abracadabra" };
std::vector<std::string> v({ "xyzzy", "plugh", "abracadabra" });
std::vector<std::string> v{ "xyzzy", "plugh", "abracadabra" }; // see "Uniform initialization" below
Uniform initializationC++03 has a number of problems with initializing types. Several ways to do this exist, and some produce different results when interchanged. The traditional constructor syntax, for example, can look like a function declaration, and steps must be taken to ensure that the compiler's most vexing parse rule will not mistake it for such. Only aggregates and POD types can be initialized with aggregate initializers (using C++11 provides a syntax that allows for fully uniform type initialization that works on any object. It expands on the initializer list syntax: struct IntAndFloat1 {
int x;
double y;
};
struct IntAndFloat2 {
private:
int x;
double y;
class:
IntAndFloat(int x, double y):
x{x}, y{y} {}
};
IntAndFloat1 var1{5, 3.2};
IntAndFloat2 var2{2, 4.3};
The initialization of One can also do this: struct IdString {
std::string name;
int identifier;
};
IdString getString() {
return {"foo", 42}; // Note the lack of explicit type.
}
Uniform initialization does not replace constructor syntax, which is still needed at times. If a class has an initializer list constructor ( std::vector<int> vec{4};
will call the initializer list constructor, not the constructor of Type inferenceIn C++03 (and C), to use a variable, its type must be specified explicitly. However, with the advent of template types and template metaprogramming techniques, the type of something, particularly the well-defined return value of a function, may not be easily expressed. Thus, storing intermediates in variables is difficult, possibly needing knowledge of the internals of a given metaprogramming library. C++11 allows this to be mitigated in two ways. First, the definition of a variable with an explicit initialization can use the auto some_strange_callable_type = std::bind(&some_function, _2, _1, some_object);
auto other_variable = 5;
The type of This use of the keyword Further, the keyword int some_int;
decltype(some_int) other_integer_variable = 5;
This is more useful in conjunction with
for (std::vector<int>::const_iterator itr = myvec.cbegin(); itr != myvec.cend(); ++itr)
the programmer can use the shorter for (auto itr = myvec.cbegin(); itr != myvec.cend(); ++itr)
which can be further compacted since "myvec" implements begin/end iterators: for (const auto& x : myvec)
This difference grows as the programmer begins to nest containers, though in such cases The type denoted by #include <vector>
int main()
{
const std::vector<int> v(1);
auto a = v[0]; // a has type int
decltype(v[0]) b = 1; // b has type const int&, the return type of
// std::vector<int>::operator[](size_type) const
auto c = 0; // c has type int
auto d = c; // d has type int
decltype(c) e; // e has type int, the type of the entity named by c
decltype((c)) f = c; // f has type int&, because (c) is an lvalue
decltype(0) g; // g has type int, because 0 is an rvalue
}
Range-based for loopC++11 extends the syntax of the int my_array[5] = {1, 2, 3, 4, 5};
// double the value of each element in my_array:
for (int& x : my_array)
x *= 2;
// similar but also using type inference for array elements
for (auto& x : my_array)
x *= 2;
This form of Lambda functions and expressionsC++11 provides the ability to create anonymous functions, called lambda functions.[14] These are defined as follows: [](int x, int y) -> int { return x + y; }
The return type ( Alternative function syntaxStandard C function declaration syntax was perfectly adequate for the feature set of the C language. As C++ evolved from C, it kept the basic syntax and extended it where needed. However, as C++ grew more complex, it exposed several limits, especially regarding template function declarations. For example, in C++03 this is invalid: template<class Lhs, class Rhs>
Ret adding_func(const Lhs &lhs, const Rhs &rhs) {return lhs + rhs;} //Ret must be the type of lhs+rhs
The type template<class Lhs, class Rhs>
decltype(lhs+rhs) adding_func(const Lhs &lhs, const Rhs &rhs) {return lhs + rhs;} //Not valid C++11
This is not valid C++ because To work around this, C++11 introduced a new function declaration syntax, with a trailing-return-type:[15] template<class Lhs, class Rhs>
auto adding_func(const Lhs &lhs, const Rhs &rhs) -> decltype(lhs+rhs) {return lhs + rhs;}
This syntax can be used for more mundane function declarations and definitions: struct SomeStruct
{
auto func_name(int x, int y) -> int;
};
auto SomeStruct::func_name(int x, int y) -> int
{
return x + y;
}
The use of the “auto” keyword in this case is just part of the syntax and does not perform automatic type deduction in C++11. However, starting with C++14, the trailing return type can be removed entirely and the compiler will deduce the return type automatically.[16] Object construction improvementIn C++03, constructors of a class are not allowed to call other constructors in an initializer list of that class. Each constructor must construct all of its class members itself or call a common member function, as follows: class SomeType
{
public:
SomeType(int new_number)
{
Construct(new_number);
}
SomeType()
{
Construct(42);
}
private:
void Construct(int new_number)
{
number = new_number;
}
int number;
};
Constructors for base classes cannot be directly exposed to derived classes; each derived class must implement constructors even if a base class constructor would be appropriate. Non-constant data members of classes cannot be initialized at the site of the declaration of those members. They can be initialized only in a constructor. C++11 provides solutions to all of these problems. C++11 allows constructors to call other peer constructors (termed delegation). This allows constructors to utilize another constructor's behavior with a minimum of added code. Delegation has been used in other languages e.g., Java and Objective-C. This syntax is as follows: class SomeType
{
int number;
public:
SomeType(int new_number) : number(new_number) {}
SomeType() : SomeType(42) {}
};
In this case, the same effect could have been achieved by making This comes with a caveat: C++03 considers an object to be constructed when its constructor finishes executing, but C++11 considers an object constructed once any constructor finishes execution. Since multiple constructors will be allowed to execute, this will mean that each delegating constructor will be executing on a fully constructed object of its own type. Derived class constructors will execute after all delegation in their base classes is complete. For base-class constructors, C++11 allows a class to specify that base class constructors will be inherited. Thus, the C++11 compiler will generate code to perform the inheritance and the forwarding of the derived class to the base class. This is an all-or-nothing feature: either all of that base class's constructors are forwarded or none of them are. Also, an inherited constructor will be shadowed if it matches the signature of a constructor of the derived class, and restrictions exist for multiple inheritance: class constructors cannot be inherited from two classes that use constructors with the same signature. The syntax is as follows: class BaseClass
{
public:
BaseClass(int value);
};
class DerivedClass : public BaseClass
{
public:
using BaseClass::BaseClass;
};
For member initialization, C++11 allows this syntax: class SomeClass
{
public:
SomeClass() {}
explicit SomeClass(int new_value) : value(new_value) {}
private:
int value = 5;
};
Any constructor of the class will initialize It can also use constructor or uniform initialization, instead of the assignment initialization shown above. Explicit overrides and finalIn C++03, it is possible to accidentally create a new virtual function, when one intended to override a base class function. For example: struct Base
{
virtual void some_func(float);
};
struct Derived : Base
{
virtual void some_func(int);
};
Suppose the C++11 provides syntax to solve this problem. struct Base
{
virtual void some_func(float);
};
struct Derived : Base
{
virtual void some_func(int) override; // ill-formed - doesn't override a base class method
};
The C++11 also adds the ability to prevent inheriting from classes or simply preventing overriding methods in derived classes. This is done with the special identifier struct Base1 final { };
struct Derived1 : Base1 { }; // ill-formed because the class Base1 has been marked final
struct Base2
{
virtual void f() final;
};
struct Derived2 : Base2
{
void f(); // ill-formed because the virtual function Base2::f has been marked final
};
In this example, the Neither
Null pointer constant and typeFor the purposes of this section and this section alone, every occurrence of " Since the dawn of C in 1972, the constant void foo(char *);
void foo(int);
If C++11 corrects this by introducing a new keyword to serve as a distinguished null pointer constant: For backwards compatibility reasons, char *pc = nullptr; // OK
int *pi = nullptr; // OK
bool b = nullptr; // OK. b is false.
int i = nullptr; // error
foo(nullptr); // calls foo(nullptr_t), not foo(int);
/*
Note that foo(nullptr_t) will actually call foo(char *) in the example above using an implicit conversion,
only if no other functions are overloading with compatible pointer types in scope.
If multiple overloadings exist, the resolution will fail as it is ambiguous,
unless there is an explicit declaration of foo(nullptr_t).
In standard types headers for C++11, the nullptr_t type should be declared as:
typedef decltype(nullptr) nullptr_t;
but not as:
typedef int nullptr_t; // prior versions of C++ which need NULL to be defined as 0
typedef void *nullptr_t; // ANSI C which defines NULL as ((void*)0)
*/
Strongly typed enumerationsIn C++03, enumerations are not type-safe. They are effectively integers, even when the enumeration types are distinct. This allows the comparison between two enum values of different enumeration types. The only safety that C++03 provides is that an integer or a value of one enum type does not convert implicitly to another enum type. Further, the underlying integral type is implementation-defined; code that depends on the size of the enumeration is thus non-portable. Lastly, enumeration values are scoped to the enclosing scope. Thus, it is not possible for two separate enumerations in the same scope to have matching member names. C++11 allows a special classification of enumeration that has none of these issues. This is expressed using the enum class Enumeration
{
Val1,
Val2,
Val3 = 100,
Val4 // = 101
};
This enumeration is type-safe. Enum class values are not implicitly converted to integers. Thus, they cannot be compared to integers either (the expression The underlying type of enum classes is always known. The default type is enum class Enum2 : unsigned int {Val1, Val2};
With old-style enumerations the values are placed in the outer scope. With new-style enumerations they are placed within the scope of the enum class name. So in the above example, There is also a transitional syntax to allow old-style enumerations to provide explicit scoping, and the definition of the underlying type: enum Enum3 : unsigned long {Val1 = 1, Val2};
In this case the enumerator names are defined in the enumeration's scope ( Forward-declaring enums is also possible in C++11. Formerly, enum types could not be forward-declared because the size of the enumeration depends on the definition of its members. As long as the size of the enumeration is specified either implicitly or explicitly, it can be forward-declared: enum Enum1; // Invalid in C++03 and C++11; the underlying type cannot be determined.
enum Enum2 : unsigned int; // Valid in C++11, the underlying type is specified explicitly.
enum class Enum3; // Valid in C++11, the underlying type is int.
enum class Enum4 : unsigned int; // Valid in C++11.
enum Enum2 : unsigned short; // Invalid in C++11, because Enum2 was formerly declared with a different underlying type.
Right angle bracketC++03's parser defines “ C++11 improves the specification of the parser so that multiple right angle brackets will be interpreted as closing the template argument list where it is reasonable. This can be overridden by using parentheses around parameter expressions using the “ template<bool Test> class SomeType;
std::vector<SomeType<1>2>> x1; // Interpreted as a std::vector of SomeType<true>,
// followed by "2 >> x1", which is not valid syntax for a declarator. 1 is true.
std::vector<SomeType<(1>2)>> x1; // Interpreted as std::vector of SomeType<false>,
// followed by the declarator "x1", which is valid C++11 syntax. (1>2) is false.
Explicit conversion operatorsC++98 added the In C++11, the For example, this feature solves cleanly the safe bool issue. Template aliasesIn C++03, it is possible to define a typedef only as a synonym for another type, including a synonym for a template specialization with all actual template arguments specified. It is not possible to create a typedef template. For example: template <typename First, typename Second, int Third>
class SomeType;
template <typename Second>
typedef SomeType<OtherType, Second, 5> TypedefName; // Invalid in C++03
This will not compile. C++11 adds this ability with this syntax: template <typename First, typename Second, int Third>
class SomeType;
template <typename Second>
using TypedefName = SomeType<OtherType, Second, 5>;
The typedef void (*FunctionType)(double); // Old style
using FunctionType = void (*)(double); // New introduced syntax
Unrestricted unionsIn C++03, there are restrictions on what types of objects can be members of a If a This is a simple example of a union permitted in C++11: #include <new> // Needed for placement 'new'.
struct Point
{
Point() {}
Point(int x, int y): x_(x), y_(y) {}
int x_, y_;
};
union U
{
int z;
double w;
Point p; // Invalid in C++03; valid in C++11.
U() {} // Due to the Point member, a constructor definition is now needed.
U(const Point& pt) : p(pt) {} // Construct Point object using initializer list.
U& operator=(const Point& pt) { new(&p) Point(pt); return *this; } // Assign Point object using placement 'new'.
};
The changes will not break any existing code since they only relax current rules. Core language functionality improvementsThese features allow the language to do things that were formerly impossible, exceedingly verbose, or needed non-portable libraries. Variadic templatesIn C++11, templates can take variable numbers of template parameters. This also allows the definition of type-safe variadic functions. New string literalsC++03 offers two kinds of string literals. The first kind, contained within double quotes, produces a null-terminated array of type C++11 supports three Unicode encodings: UTF-8, UTF-16, and UTF-32. The definition of the type Creating string literals for each of the supported encodings can be done thus: u8"I'm a UTF-8 string."
u"This is a UTF-16 string."
U"This is a UTF-32 string."
The type of the first string is the usual When building Unicode string literals, it is often useful to insert Unicode code points directly into the string. To do this, C++11 allows this syntax: u8"This is a Unicode Character: \u2018."
u"This is a bigger Unicode Character: \u2018."
U"This is a Unicode Character: \U00002018."
The number after the It is also sometimes useful to avoid escaping strings manually, particularly for using literals of XML files, scripting languages, or regular expressions. C++11 provides a raw string literal: R"(The String Data \ Stuff " )" R"delimiter(The String Data \ Stuff " )delimiter" In the first case, everything between the Raw string literals can be combined with the wide literal or any of the Unicode literal prefixes: u8R"XXX(I'm a "raw UTF-8" string.)XXX" uR"*(This is a "raw UTF-16" string.)*" UR"(This is a "raw UTF-32" string.)" User-defined literalsC++03 provides a number of literals. The characters By contrast, C++11 enables the user to define new kinds of literal modifiers that will construct objects based on the string of characters that the literal modifies. Transformation of literals is redefined into two distinct phases: raw and cooked. A raw literal is a sequence of characters of some specific type, while the cooked literal is of a separate type. The C++ literal Literals can be extended in both raw and cooked forms, with the exception of string literals, which can be processed only in cooked form. This exception is due to the fact that strings have prefixes that affect the specific meaning and type of the characters in question. All user-defined literals are suffixes; defining prefix literals is not possible. All suffixes starting with any character except underscore ( User-defined literals processing the raw form of the literal are defined via a literal operator, which is written as OutputType operator "" _mysuffix(const char * literal_string)
{
// assumes that OutputType has a constructor that takes a const char *
OutputType ret(literal_string);
return ret;
}
OutputType some_variable = 1234_mysuffix;
// assumes that OutputType has a get_value() method that returns a double
assert(some_variable.get_value() == 1234.0)
The assignment statement An alternative mechanism for processing integer and floating point raw literals is via a variadic template: template<char...> OutputType operator "" _tuffix();
OutputType some_variable = 1234_tuffix;
OutputType another_variable = 2.17_tuffix;
This instantiates the literal processing function as For numeric literals, the type of the cooked literal is either OutputType operator "" _suffix(unsigned long long);
OutputType operator "" _suffix(long double);
OutputType some_variable = 1234_suffix; // Uses the 'unsigned long long' overload.
OutputType another_variable = 3.1416_suffix; // Uses the 'long double' overload.
In accord with the formerly mentioned new string prefixes, for string literals, these are used: OutputType operator "" _ssuffix(const char * string_values, size_t num_chars);
OutputType operator "" _ssuffix(const wchar_t * string_values, size_t num_chars);
OutputType operator "" _ssuffix(const char16_t * string_values, size_t num_chars);
OutputType operator "" _ssuffix(const char32_t * string_values, size_t num_chars);
OutputType some_variable = "1234"_ssuffix; // Uses the 'const char *' overload.
OutputType some_variable = u8"1234"_ssuffix; // Uses the 'const char *' overload.
OutputType some_variable = L"1234"_ssuffix; // Uses the 'const wchar_t *' overload.
OutputType some_variable = u"1234"_ssuffix; // Uses the 'const char16_t *' overload.
OutputType some_variable = U"1234"_ssuffix; // Uses the 'const char32_t *' overload.
There is no alternative template form. Character literals are defined similarly. Multithreading memory modelC++11 standardizes support for multithreaded programming. There are two parts involved: a memory model which allows multiple threads to co-exist in a program and library support for interaction between threads. (See this article's section on threading facilities.) The memory model defines when multiple threads may access the same memory location, and specifies when updates by one thread become visible to other threads. Thread-local storageIn a multi-threaded environment, it is common for every thread to have some unique variables. This already happens for the local variables of a function, but it does not happen for global and static variables. A new thread-local storage duration (in addition to the existing static, dynamic and automatic) is indicated by the storage specifier Any object which could have static storage duration (i.e., lifetime spanning the entire execution of the program) may be given thread-local duration instead. The intent is that like any other static-duration variable, a thread-local object can be initialized using a constructor and destroyed using a destructor. Explicitly defaulted special member functionsIn C++03, the compiler provides, for classes that do not provide them for themselves, a default constructor, a copy constructor, a copy assignment operator ( However, there is very little control over creating these defaults. Making a class inherently non-copyable, for example, may be done by declaring a private copy constructor and copy assignment operator and not defining them. Attempting to use these functions is a violation of the One Definition Rule (ODR). While a diagnostic message is not required,[19] violations may result in a linker error. In the case of the default constructor, the compiler will not generate a default constructor if a class is defined with any constructors. This is useful in many cases, but it is also useful to be able to have both specialized constructors and the compiler-generated default. C++11 allows the explicit defaulting and deleting of these special member functions.[20] For example, this class explicitly declares that a default constructor can be used: class SomeType
{
SomeType() = default; //The default constructor is explicitly stated.
SomeType(OtherType value);
};
Explicitly deleted functionsA function can be explicitly disabled. This is useful for preventing implicit type conversions.
The void noInt(double i);
void noInt(int) = delete;
An attempt to call It is possible to prohibit calling the function with any type other than double onlyDouble(double d) {return d;}
template<typename T> double onlyDouble(T) = delete;
calling Class member functions and constructors can also be deleted. For example, it is possible to prevent copying class objects by deleting the copy constructor and class NonCopyable
{
NonCopyable();
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator=(const NonCopyable&) = delete;
};
Type |
Type of hash table | Associated values | Equivalent keys |
---|---|---|
std::unordered_set |
No | No |
std::unordered_multiset |
No | Yes |
std::unordered_map |
Yes | No |
std::unordered_multimap |
Yes | Yes |
The new classes fulfill all the requirements of a container class, and have all the methods needed to access elements: insert
, erase
, begin
, end
.
This new feature didn't need any C++ language core extensions (though implementations will take advantage of various C++11 language features), only a small extension of the header <functional>
and the introduction of headers <unordered_set>
and <unordered_map>
. No other changes to any existing standard classes were needed, and it doesn't depend on any other extensions of the standard library.
std::array and std::forward_list
In addition to the hash tables two more containers was added to the standard library. The std::array is a fixed size container that is more efficient than std::vector but safer and easier to use than a c-style array. The std::forward_list is a single linked list that provides more space efficient storage than the double linked std::list when bidirectional iteration is not needed.
Regular expressions
The new library, defined in the new header <regex>
, is made of a couple of new classes:
- regular expressions are represented by instance of the template class
std::regex
; - occurrences are represented by instance of the template class
std::match_results
, - std::regex_iterator is used to iterate over all matches of a regex
The function std::regex_search
is used for searching, while for ‘search and replace’ the function std::regex_replace
is used which returns a new string.[25]
Here is an example of the use of std::regex_iterator
:
#include <regex>
const char *pattern = R"([^ ,.\t\n]+)"; // find words separated by space, comma, period tab newline
std::regex rgx(pattern); // throws exception on invalid pattern
const char *target = "Unseen University - Ankh-Morpork";
// Use a regex_iterator to identify all words of 'target' separated by characters of 'pattern'.
auto iter =
std::cregex_iterator(target, target + strlen(target), rgx);
// make an end of sequence iterator
auto end =
std::cregex_iterator();
for (; iter != end; ++iter)
{
std::string match_str = iter->str();
std::cout << match_str << '\n';
}
The library <regex>
requires neither alteration of any existing header (though it will use them where appropriate) nor an extension of the core language. In POSIX C, regular expressions are also available via the C POSIX library#regex.h.
General-purpose smart pointers
C++11 provides std::unique_ptr
, and improvements to std::shared_ptr
and std::weak_ptr
from TR1. std::auto_ptr
is deprecated.
Extensible random number facility
The C standard library provides the ability to generate pseudorandom numbers via the function rand
. However, the algorithm is delegated entirely to the library vendor. C++ inherited this functionality with no changes, but C++11 provides a new method for generating pseudorandom numbers.
C++11's random number functionality is split into two parts: a generator engine that contains the random number generator's state and produces the pseudorandom numbers; and a distribution, which determines the range and mathematical distribution of the outcome. These two are combined to form a random number generator object.
Unlike the C standard rand
, the C++11 mechanism will come with three base generator engine algorithms:
C++11 also provides a number of standard distributions:
uniform_int_distribution
,uniform_real_distribution
,bernoulli_distribution
,binomial_distribution
,geometric_distribution
,negative_binomial_distribution
,poisson_distribution
,exponential_distribution
,gamma_distribution
,weibull_distribution
,extreme_value_distribution
,normal_distribution
,lognormal_distribution
,chi_squared_distribution
,cauchy_distribution
,fisher_f_distribution
,student_t_distribution
,discrete_distribution
,piecewise_constant_distribution
andpiecewise_linear_distribution
.
The generator and distributions are combined as in this example:
#include <random>
#include <functional>
std::uniform_int_distribution<int> distribution(0, 99);
std::mt19937 engine; // Mersenne twister MT19937
auto generator = std::bind(distribution, engine);
int random = generator(); // Generate a uniform integral variate between 0 and 99.
int random2 = distribution(engine); // Generate another sample directly using the distribution and the engine objects.
Wrapper reference
A wrapper reference is obtained from an instance of the class template reference_wrapper
. Wrapper references are similar to normal references (‘&
’) of the C++ language. To obtain a wrapper reference from any object the function template ref
is used (for a constant reference cref
is used).
Wrapper references are useful above all for function templates, where references to parameters rather than copies are needed:
// This function will take a reference to the parameter 'r' and increment it.
void func (int &r) { r++; }
// Template function.
template<class F, class P> void g (F f, P t) { f(t); }
int main()
{
int i = 0;
g (func, i); // 'g<void (int &r), int>' is instantiated
// then 'i' will not be modified.
std::cout << i << std::endl; // Output -> 0
g (func, std::ref(i)); // 'g<void(int &r),reference_wrapper<int>>' is instantiated
// then 'i' will be modified.
std::cout << i << std::endl; // Output -> 1
}
This new utility was added to the existing <functional>
header and didn't need further extensions of the C++ language.
Polymorphic wrappers for function objects
Polymorphic wrappers for function objects are similar to function pointers in semantics and syntax, but are less tightly bound and can indiscriminately refer to anything which can be called (function pointers, member function pointers, or functors) whose arguments are compatible with those of the wrapper.
An example can clarify its characteristics:
std::function<int (int, int)> func; // Wrapper creation using
// template class 'function'.
std::plus<int> add; // 'plus' is declared as 'template<class T> T plus( T, T ) ;'
// then 'add' is type 'int add( int x, int y )'.
func = add; // OK - Parameters and return types are the same.
int a = func (1, 2); // NOTE: if the wrapper 'func' does not refer to any function,
// the exception 'std::bad_function_call' is thrown.
std::function<bool (short, short)> func2 ;
if (!func2)
{
// True because 'func2' has not yet been assigned a function.
bool adjacent(long x, long y);
func2 = &adjacent; // OK - Parameters and return types are convertible.
struct Test
{
bool operator()(short x, short y);
};
Test car;
func = std::ref(car); // 'std::ref' is a template function that returns the wrapper
// of member function 'operator()' of struct 'car'.
}
func = func2; // OK - Parameters and return types are convertible.
The template class function
was defined inside the header <functional>
, without needing any change to the C++ language.
Type traits for metaprogramming
Metaprogramming consists of creating a program that creates or modifies another program (or itself). This can happen during compilation or during execution. The C++ Standards Committee has decided to introduce a library for metaprogramming during compiling via templates.
Here is an example of a meta-program using the C++03 standard: a recursion of template instances for calculating integer exponents:
template<int B, int N>
struct Pow
{
// recursive call and recombination.
enum{ value = B*Pow<B, N-1>::value };
};
template< int B >
struct Pow<B, 0>
{
// ''N == 0'' condition of termination.
enum{ value = 1 };
};
int quartic_of_three = Pow<3, 4>::value;
Many algorithms can operate on different types of data; C++'s templates support generic programming and make code more compact and useful. Nevertheless, it is common for algorithms to need information on the data types being used. This information can be extracted during instantiation of a template class using type traits.
Type traits can identify the category of an object and all the characteristics of a class (or of a struct). They are defined in the new header <type_traits>
.
In the next example there is the template function ‘elaborate’ which, depending on the given data types, will instantiate one of the two proposed algorithms (Algorithm::do_it
).
// First way of operating.
template< bool B > struct Algorithm
{
template<class T1, class T2> static int do_it (T1 &, T2 &) { /*...*/ }
};
// Second way of operating.
template<> struct Algorithm<true>
{
template<class T1, class T2> static int do_it (T1, T2) { /*...*/ }
};
// Instantiating 'elaborate' will automatically instantiate the correct way to operate.
template<class T1, class T2>
int elaborate (T1 A, T2 B)
{
// Use the second way only if 'T1' is an integer and if 'T2' is
// in floating point, otherwise use the first way.
return Algorithm<std::is_integral<T1>::value && std::is_floating_point<T2>::value>::do_it( A, B ) ;
}
Via type traits, defined in header <type_traits>
, it's also possible to create type transformation operations (static_cast
and const_cast
are insufficient inside a template).
This type of programming produces elegant and concise code; however, the weak point of these techniques is the debugging: it's uncomfortable during compilation and very difficult during program execution.
Uniform method for computing the return type of function objects
Determining the return type of a template function object at compile-time is not intuitive, particularly if the return value depends on the parameters of the function. As an example:
struct Clear
{
int operator()(int) const; // The parameter type is
double operator()(double) const; // equal to the return type.
};
template <class Obj>
class Calculus
{
public:
template<class Arg> Arg operator()(Arg& a) const
{
return member(a);
}
private:
Obj member;
};
Instantiating the class template Calculus<Clear>
, the function object of calculus
will have always the same return type as the function object of Clear
. However, given class Confused
below:
struct Confused
{
double operator()(int) const; // The parameter type is not
int operator()(double) const; // equal to the return type.
};
Attempting to instantiate Calculus<Confused>
will cause the return type of Calculus
to not be the same as that of class Confused
. The compiler may generate warnings about the conversion from int
to double
and vice versa.
TR1 introduces, and C++11 adopts, the template class std::result_of
that allows one to determine and use the return type of a function object for every declaration. The object CalculusVer2
uses the std::result_of
object to derive the return type of the function object:
template< class Obj >
class CalculusVer2
{
public:
template<class Arg>
typename std::result_of<Obj(Arg)>::type operator()(Arg& a) const
{
return member(a);
}
private:
Obj member;
};
In this way in instances of function object of CalculusVer2<Confused>
there are no conversions, warnings, or errors.
The only change from the TR1 version of std::result_of
is that the TR1 version allowed an implementation to fail to be able to determine the result type of a function call. Due to changes to C++ for supporting decltype
, the C++11 version of std::result_of
no longer needs these special cases; implementations are required to compute a type in all cases.
Improved C compatibility
For compatibility with C, from C99, these were added:[26]
- Preprocessor:[27]
- variadic macros,
- concatenation of adjacent narrow/wide string literals,
_Pragma()
– equivalent of#pragma
.
long long
– integer type that is at least 64 bits long.__func__
– macro evaluating to the name of the function it is in.- Headers:
cstdbool
(stdbool.h
),cstdint
(stdint.h
),cinttypes
(inttypes.h
).
Features originally planned but removed or not included
Heading for a separate TR:
- Modules
- Decimal types
- Math special functions
Postponed:
- Concepts
- More complete or required garbage collection support
- Reflection
- Macro scopes
Features removed or deprecated
The term sequence point was removed, being replaced by specifying that either one operation is sequenced before another, or that two operations are unsequenced.[28]
The former use of the keyword export
was removed.[29] The keyword itself remains, being reserved for potential future use.
Dynamic exception specifications are deprecated.[29] Compile-time specification of non-exception-throwing functions is available with the noexcept
keyword, which is useful for optimization.
std::auto_ptr
is deprecated, having been superseded by std::unique_ptr
.
Function object base classes (std::unary_function
, std::binary_function
), adapters to pointers to functions and adapters to pointers to members, and binder classes are all deprecated.
Annex D.2 states: "The use of the register
keyword as a storage-class-specifier (§7.1.1) is deprecated."
See also
References
- ^ "We have an international standard: C++0x is unanimously approved". 12 August 2011. Archived from the original on 11 December 2018. Retrieved 12 August 2011.
- ^ a b Stroustrup, Bjarne. "C++11 FAQ". stroustrup.com. Archived from the original on 2018-10-06. Retrieved 2014-10-15.
- ^ a b "C++11 Overview: What specific design goals guided the committee?". Standard C++. Archived from the original on 2019-01-31. Retrieved 2015-09-04.
- ^ "Bjarne Stroustrup: A C++0x overview" (PDF). Archived (PDF) from the original on 17 June 2016. Retrieved 30 June 2011.
- ^ "ISO/IEC 14882:2011". ISO. 2 September 2011. Archived from the original on 29 January 2013. Retrieved 3 September 2011.
- ^ "Working Draft, Standard for Programming Language C++" (PDF). Archived (PDF) from the original on 2019-01-21. Retrieved 2012-04-26.
- ^ "The Standard". Standard C++ Foundation. Archived from the original on 2012-11-05. Retrieved 2012-11-02.
Except only for the final standards/reports, all C++ committee documents are freely publicly available, including all working drafts, many of which closely approximate the published standard. The January 2012 working draft contains the C++11 standard plus minor editorial changes.
- ^ "Clang - C++ Programming Language Status". 2023-11-29. Archived from the original on 2023-11-29. Retrieved 2023-12-01.
- ^ "GCC 4.8.1 released, C++11 feature complete: Standard C++". isocpp.org. Retrieved 2023-12-01.
- ^ Sutter, Alexandrescu "C++ coding standards" #15
- ^ Gabriel Dos Reis; Bjarne Stroustrup (22 March 2010). "General Constant Expressions for System Programming Languages, Proceedings SAC '10" (PDF). Archived (PDF) from the original on 13 June 2018. Retrieved 18 August 2012.
- ^ Jaakko Järvi; Bjarne Stroustrup; Douglas Gregor; Jeremy Siek (April 28, 2003). "Decltype and auto, Programming Language C++, Document no: N1478=03-0061" (PDF). Archived (PDF) from the original on May 28, 2015. Retrieved June 6, 2015.
- ^ Roger Orr (June 2013). ""Auto – A Necessary Evil?" Overload Journal #115". Archived from the original on 2015-06-06. Retrieved 2015-06-06.
- ^ "Document no: N1968=06-0038- Lambda expressions and closures for C++" (PDF). Open Standards. Archived (PDF) from the original on 2011-07-28. Retrieved 2009-04-20.
- ^ "Decltype (revision 5)" (PDF). Archived (PDF) from the original on 2022-02-14. Retrieved 2022-02-16.
- ^ "auto specifier (since C++11) - cppreference.com". en.cppreference.com. Archived from the original on 2016-10-20. Retrieved 2016-10-18.
- ^ Gustedt, Jens (2019-07-09). "Introduce the nullptr constant - v1" (PDF). ISO JTC1/SC22/WG14 Document Register. International Organization for Standardization. Archived (PDF) from the original on 2020-07-27. Retrieved 2020-04-19 – via open-std.org.
- ^ This caused a conflict with the proposed use (common in other languages) of the underscore for digit grouping in numeric literals such as integer literals, so C++14 instead uses the apostrophe (as an upper comma) for grouping.Daveed Vandevoorde (2012-09-21). "N3448: Painless Digit Separation" (PDF). Archived (PDF) from the original on 2015-08-11. Retrieved 2015-08-13., Lawrence Crowl (2012-12-19). "N3499: Digit Separators". Archived from the original on 2015-08-11. Retrieved 2015-08-13.
- ^ ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages – C++ §3.2 One definition rule [basic.def.odr] para. 3
- ^ a b "Defaulted and Deleted Functions – ISO/IEC JTC1 SC22 WG21 N2210 = 07-0070 – 2007-03-11". Archived from the original on 2012-08-19. Retrieved 2012-12-20.
- ^ "Using the GNU Compiler Collection (GCC): Long Long". gcc.gnu.org. Archived from the original on 2016-08-21. Retrieved 2016-07-25.
- ^ "Data Type Ranges (C++)". Archived from the original on 2009-02-21. Retrieved 2009-04-23.
- ^ Samuel P. Harbison III, Guy L. Steele Jr.: "C – A Reference Manual", 5th edition, p.251
- ^ Milewski, Bartosz (3 March 2009). "Broken promises–C++0x futures". Archived from the original on 16 September 2011. Retrieved 24 January 2010.
- ^ "C++ Regular expressions library". cppreference.com. Retrieved 10 December 2022.
- ^ "Clang - C++98, C++11, and C++14 Status". Clang.llvm.org. 2013-05-12. Archived from the original on 2019-05-28. Retrieved 2013-06-10.
- ^ "Working draft changes for C99 preprocessor synchronization". www.open-std.org. Archived from the original on 2020-07-31. Retrieved 2014-05-26.
- ^ Caves, Jonathan (4 June 2007). "Update on the C++-0x Language Standard". Archived from the original on 9 September 2011. Retrieved 25 May 2010.
- ^ a b Sutter, Herb (3 March 2010). "Trip Report: March 2010 ISO C++ Standards Meeting". Archived from the original on 11 July 2018. Retrieved 24 March 2010.
External links
![]() | This section's use of external links may not follow Wikipedia's policies or guidelines. (October 2018) |
- The C++ Standards Committee
- C++0X: The New Face of Standard C++
- Herb Sutter's blog coverage of C++11
- Anthony Williams' blog coverage of C++11
- A talk on C++0x given by Bjarne Stroustrup at the University of Waterloo Archived 2009-01-23 at the Wayback Machine
- The State of the Language: An Interview with Bjarne Stroustrup (15 August 2008) Archived 31 January 2009 at the Wayback Machine
- Wiki page to help keep track of C++ 0x core language features and their availability in compilers
- Online C++11 standard library reference
- Online C++11 compiler
- Bjarne Stroustrup's C++11 FAQ
- More information on C++11 features:range-based for loop, why auto_ptr is deprecated, etc. [usurped]