C++11 Is A Version of The Standard For The Programming
C++11 Is A Version of The Standard For The Programming
C++11 Is A Version of The Standard For The Programming
EN
C++11
Connected to:
C++C++03Core language
From Wikipedia, the free encyclopedia
This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when
to remove these template messages) This article may have too many section headers dividing up its content. Please
help improve the article by merging similar sections and removing unneeded subheaders. (March 2017) This article
may be too technical for most readers to understand. Please help improve it to make it understandable to non-experts,
without removing the technical details. (March 2017) (Learn how and when to remove this template message) (Learn
how and when to remove this template message)
Design goals
This section does not cite any sources. Please help improve this section by adding citations to reliable sources.
Unsourced material may be challenged and removed. (August 2018) (Learn how and when to remove this template
message)
rewritten as follows:
constexpr int get_five() {return 5;}
Initializer lists
C++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 Object
{
float first;
int second;
};
Object scalar = {0.43f, 10}; //One Object, with first=0.43f and second=10
Object 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 std::vector.
C++11 binds the concept to a template,
called std::initializer_list. This allows
constructors and other functions to take initializer-lists as
parameters. For example:
class SequenceClass
{
public:
SequenceClass(std::initializer_list<int> list);
};
Uniform initialization
C++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 SomeType var = {/*stuff*/};).
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 BasicStruct
{
int x;
double y;
};
struct AltStruct
{
AltStruct(int x, double y)
: x_{x}
, y_{y}
{}
private:
int x_;
double y_;
};
IdString get_string()
{
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
(TypeName(initializer_list<SomeType>);),
then it takes priority over other forms of construction,
provided that the initializer list conforms to the sequence
constructor's type. The C++11 version
of std::vector has an initializer list constructor for its
template type. Thus this code:
std::vector<int> the_vec{4};
This is not valid C++ because lhs and rhs have not yet
been defined; they will not be valid identifiers until after the
parser has parsed the rest of the function prototype.
To work around this, C++11 introduced a new function
declaration syntax, with a trailing-return-type:
template<class Lhs, class Rhs>
auto adding_func(const Lhs &lhs, const Rhs &rhs) -> decltype(lhs+rhs)
{return lhs + rhs;}
SomeType()
{
Construct(42);
}
private:
void Construct(int new_number)
{
number = new_number;
}
int number;
};
public:
SomeType(int new_number) : number(new_number) {}
SomeType() : SomeType(42) {}
};
Notice that, in this case, the same effect could have been
achieved by making new_number a defaulting parameter.
The new syntax, however, allows the default value (42) to be
expressed in the implementation rather than the interface —
a benefit to maintainers of library code since default values
for function parameters are “baked in” to call sites, whereas
constructor delegation allows the value to be changed
without recompilation of the code using the library.
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);
};
private:
int value = 5;
};
struct Derived1 : Base1 { }; // ill-formed because the class Base1 has been
marked final
struct Base2
{
virtual void f() final;
};
Unrestricted unions
In C++03, there are restrictions on what types of objects can
be members of a union. For example, unions cannot
contain any objects that define a non-trivial constructor or
destructor. C++11 lifts some of these restrictions. [3]
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.
Variadic templates
Main article: Variadic template
In C++11, templates can take variable numbers of template
parameters. This also allows the definition of type-
safe variadic functions.
New string literals
C++03 offers two kinds of string literals. The first kind,
contained within double quotes, produces a null-terminated
array of type const char. The second kind, defined
as L"", produces a null-terminated array of type const
wchar_t, where wchar_t is a wide-character of
undefined size and semantics. Neither literal type offers
support for string literals with UTF-8, UTF-16, or any other
kind of Unicode encodings.
The definition of the type char has been modified to
explicitly express that it's at least the size needed to store an
eight-bit coding of UTF-8, and large enough to contain any
member of the compiler's basic execution character set. It
was formerly defined as only the latter in the C++ standard
itself, then relying on the C standard to guarantee at least 8
bits.
C++11 supports three Unicode encodings: UTF-8, UTF-16,
and UTF-32. Along with the formerly noted changes to the
definition of char, C++11 adds two new character
types: char16_t and char32_t. These are designed to
store UTF-16 and UTF-32 respectively.
Creating string literals for each of these encodings can be
done thusly:
u8"I'm a UTF-8 string."
u"This is a UTF-16 string."
U"This is a UTF-32 string."
In the first case, everything between the "( and the )" is
part of the string. The " and \ characters do not need to be
escaped. In the second case, the "delimiter( starts the
string, and it ends only when )delimiter" is reached.
The string delimiter can be any string up to 16
characters in length, including the empty string. This string
cannot contain spaces, control characters, (, ), or
the \ character. Using this delimiter string allows the user to
have ) characters within raw string literals. For
example, R"delimiter((a-z))delimiter" is
equivalent to "(a-z)". [4]
User-defined literals
C++03 provides a number of literals. The
characters 12.5 are a literal that is resolved by the compiler
as a type doublewith the value of 12.5. However, the
addition of the suffix f, as in 12.5f, creates a value of
type float that contains the value 12.5. The suffix
modifiers for literals are fixed by the C++ specification, and
C++03 code cannot create new literal modifiers.
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 1234, as a raw literal, is
this sequence of characters '1', '2', '3', '4'. As a
cooked literal, it is the integer 1234. The C++ literal 0xA in
raw form is '0', 'x', 'A', while in cooked form it is the
integer 10.
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 (_) are reserved by the standard. Thus, all
user-defined literals must have suffixes starting with an
underscore (_). [15]
Thread-local storage
In 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 thread_local.
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.
Static assertions
C++03 provides two methods to test assertions: the
macro assert and the preprocessor directive #error.
However, neither is appropriate for use in templates: the
macro tests the assertion at execution-time, while the
preprocessor directive tests the assertion during
preprocessing, which happens before instantiation of
templates. Neither is appropriate for testing properties that
are dependent on template parameters.
The new utility introduces a new way to test assertions at
compile-time, using the new keyword static_assert.
The declaration assumes this form:
static_assert (constant-expression, error-message);
decltype
default/deleted functions
Further, much time has passed since the prior C++ standard.
Much code using the standard library has been written. This
has revealed parts of the standard libraries that could use
some improving. Among the many areas of improvement
considered were standard library allocators. A new scope-
based model of allocators was included in C++11 to
supplement the prior model.
Threading facilities
While the C++03 language provides a memory model that
supports threading, the primary support for actually using
threading comes with the C++11 standard library.
A thread class (std::thread) is provided, which takes
a function object (and an optional series of arguments to pass
to it) to run in the new thread. It is possible to cause a thread
to halt until another executing thread completes, providing
thread joining support via
the std::thread::join() member function. Access is
provided, where feasible, to the underlying native thread
object(s) for platform-specific operations by
the std::thread::native_handle() member
function.
For synchronization between threads,
appropriate mutexes (std::mutex, std::recursive_
mutex, etc.) and condition
variables (std::condition_variable and std::co
ndition_variable_any) are added to the library.
These are accessible via Resource Acquisition Is
Initialization (RAII) locks
(std::lock_guard and std::unique_lock) and
locking algorithms for easy use.
For high-performance, low-level work, communicating
between threads is sometimes needed without the overhead
of mutexes. This is done using atomic operations on memory
locations. These can optionally specify the minimum
memory visibility constraints needed for an operation.
Explicit memory barriers may also be used for this purpose.
The C++11 thread library also includes futures and
promises for passing asynchronous results between threads,
and std::packaged_task for wrapping up a function
call that can generate such an asynchronous result. The
futures proposal was criticized because it lacks a way to
combine futures and check for the completion of one
promise inside a set of promises. [21]
class std::match_results.
The function std::regex_search is used for searching,
while for ‘search and replace’ the
function std::regex_replaceis used which returns a
new string. The
algorithms std::regex_search and std::regex_re
place take a regular expression and a string and write the
occurrences found in the struct std::match_results.
Here is an example of the use of std::match_results:
const char *reg_esp = "[ ,.\\t\\n;:]"; // List of separator characters.
subtract_with_carry_engine, and
mersenne_twister_engine.
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 and
piecewise_linear_distribution.
Wrapper reference
A wrapper reference is obtained from an instance of the
template class 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 obtain 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
int a = func (1, 2); // NOTE: if the wrapper 'func' does not refer to any
function,
// the exception 'std::bad_function_call' is thrown.
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.
Improved C compatibility
For compatibility with C, from C99, these were added: [22]
Preprocessor: [23]
variadic macros,
cstdint (stdint.h),
cinttypes (inttypes.h).
Features originally
planned but removed or
not included
Heading for a separate TR:
Modules
Decimal types
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. [24]
The former use of the keyword export was removed. The [25]
See also
References
External links
C++
Categories
Home
About Us
Press
Site Map
Terms Of Service
Privacy Policy
C++11
Introduction
Design goals
Extensions to the C++ core language
1. Core language runtime performance enhancements
2. Core language build-time performance enhancements
3. Core language usability enhancements
4. Core language functionality improvements
C++ standard library changes
1. Upgrades to standard library components
2. Threading facilities
3. Tuple types
4. Hash tables
5. Regular expressions
6. General-purpose smart pointers
7. Extensible random number facility
8. Wrapper reference
9. Polymorphic wrappers for function objects
10. Type traits for metaprogramming
11. Uniform method for computing the return type of function
objects
Improved C compatibility
Features originally planned but removed or not
included
Features removed or deprecated
See also
References
External links