C++09: A Glimpse into the Future


英文原文: http://www.devsource.com/c/a/Languages/C09-A-Glimpse-into-the-Future/

原作者:Danny Kalev


C++09: A Glimpse into the Future


Following the Portland meeting in October 2006, the C++ standardization committee set 2009 as the target date for C++09, the next C++ standard. C++09 will include at least two major core features: rvalue references and type concepts. Other core features are also included, such as automatic deduction of types from initializers, delegating constructors, nullptr, and even a solution to the right angle bracket nuisance. Join me for an overview of core C++09.


C++09: A Glimpse into the Future - ' Rvalue References '


C++: the State of the Art


Today's C++ already provides significant enhancement to C++98. These include subtle technical corrigenda such as vector's contiguity. However, the most important change between C++98 and C++03 is the addition of TR1 libraries which include hashed containers, regular expressions, tuples, new smart pointer classes, and an array class template.


A detailed description of TR1 libraries is available here.


TR1-enabled implementations of the Standard Library are already available. TR1 was only the aperitif, though. Core C++ is heading for no less than a revolution.


Rvalue References


C++09 introduces a new category of reference types called rvalue references. Consequently, the traditional reference types that you've been using for decades are now called lvalue references. Unlike lvalue references, rvalue references can bind to rvalues even if they are not const qualified. Rvalue references enable programmers to:


* Eliminate unnecessary and expensive copies of objects by means of implementing move semantics

* Permit users to implement perfect forwarding, thereby solve major usability problems with generic libraries

* Solve usability problems in components where binding an rvalue to a non-const reference is not a logical error




Before discussing the importance of move semantics, let's look at the syntax of rvalue references. Whereas T& denotes an lvalue reference to T, T&& is an rvalue reference to T. Consider:


void g(int & n);

void h(int&& n);

g(5); //error, 5 is an rvalue

g(int()); //error, temporaries are rvalues

h(5); //OK

h(int()); //OK

S s;

S& rs=s; //ordindary lvalue reference

S&& rrs=S(); //OK, bind a temporary to an rvalue reference

S& illegal = S();//error, bind a temp to an lvalue reference

The Move Movement

C++ has been a copy-semantics language since its inception. Elementary language constructs such as copy constructors, assignment expressions, and argument passing are based on copying an existing object into a new target object. This notion is so fundamental in C++ that it takes time to grasp how significantly different move semantics is. Put simply, moving means constructing the target object directly into the source object. Consequently, you end up having a single object with a new state rather than having two objects that are copies of each other.


C++98 already implements move semantics in several places. The Named Return Value Optimization is a manifestation of the move semantics.


The swap() member function of STL containers also implements move semantics. When you swap two vectors using vector::swap(), the two containers don't copy-construct their elements in new memory destinations; they merely exchange a few pointers and flags. The performance gain can be dramatic. Copying a container of N elements is a linear operation that involves N copy constructor calls + N destructor calls. By contrast, moving is a fast constant time operation.


Another instance of move semantics is the std::auto_ptr class. It has been considered the step child of the Standard Library due to its "peculiar" copy semantics (which is actually pure move semantics!). However, with the advent of rvalue references, it is likely that move-based algorithms and containers will re-enliven the interest in classes such as auto_ptr.


C++09: A Glimpse into the Future - ' Type Concepts '


Type Concepts


Ever since their introduction, C++ templates have suffered from one significant limitation, namely the lack of a mechanism for defining and enforcing constraints on templates. Common workarounds, such as tag dispatching and type traits are inherently complex, verbose and don't guarantee early detection of constraint violations. In some cases, there's simply no way to enforce a constraint at compile time.

自从C++引入模板,它就已经忍受一个重要的缺憾,即缺少某种机制在模板上定义和实施约束。通用的替代品如tag dispatchingtype traits,天生就是复杂的和冗长的,亦不能保证尽早发现违背约束之事。在某些情况下,若要在编译时实施约束,它显得无能为力。

Douglas Gregor and Bjarne Stroustrup's concepts proposal puts an end to this embarrassment. The concepts proposal introduces a separate type-checking system for templates. Template declarations are augmented with a set of requirements known as a concept. When a template is instantiated, the compiler checks whether the instantiation complies with the concept's requirements.

Douglas GregorBjarnet Stroustrupconcepts提案给这尴尬画了句号。该concepts提案给模板引入一种分离的类型测检系统定义模板时加入一组称为concept约束条件,实例化模板时,编译器检查该实例是否满足concept约束条件

Consider the std::min() algorithm:

template<typename T>

const T& min(const T& x, const T& y)


return x < y? x : y;


The user has to examine the body of min() to know what the requirements from T are. In this case, T must be a type that has an operator< taking two references to T and returning a Boolean result. With concepts, this requirement can be expressed as follows:


auto concept LessThanComparable


bool operator<(T, T);


The definition of min() uses this concept as follows:


template<LessThanComparable T> //T must be a LessThanComparable type

const T& min(const T& x, const T& y)


return x < y? x : y;


Henceforth, whenever the compiler encounters an instantiation of min, it checks whether T meets the LessThanComparable requirements before generating the code for that instantiation. If T isn't LessThanComparable a descriptive error message will be issued.


Removing Tiny Annoyances from C++

C++09 includes a few core language changes that remove inelegance and minor annoyances.

The angle brackets proposal removes a long standing syntactic displeasure, i.e., the requirement that the right angle brackets of a nested template argument shall be separated with spaces:



vector <list <int>> vli; //compilation error; >> treated as a right shift operator

vector <list <int> > vli; //OK

The rationale behind this C++98 restriction was the "maximal munch" rule. However, current C++ compilers are smart enough to figure out that the last >> belong to two templates, so there's no reason to burden programmers with this restriction anymore. (It is legal to use spaces in C++09, though.)


nullptr is another simple yet welcome addition to C++. Many programming languages have a specific keyword that designates a null pointer or reference. C++ uses the literal 0 for this purpose. This hack causes ambiguity problems, particularly in overload resolution. The proposed nullptr solves this problem:


void f(char *);

void f(int);

f(nullptr); //calls func (char*) because nullptr isn't int

f(0); //calls func(int)

Delegating constructors (also known as forwarding constructors) will make C# and Java newcomers feel at home when using C++09. A delegating constructor uses a member initializer list that invokes another constructor (called the target constructor) of the same class. Once the target constructor returns, the delegating constructor may perform additional operations. This way, common initialization operations are encapsulated in one constructor of the class, instead of being repeated in every constructor:


struct S



S() {cout<<"target ctor"<<endl;} #1


S(bool b): S() {cout<<"delegating ctor"<<endl;} //invokes target ctor first


S obj(false);

The output shows the constructor execution order:


target ctor

delegating ctor

The Road Ahead


Additional C++09 features include, among the rest:

* extern templates (not to be confused with exported templates) which is a mechanism for suppressing the implicit instantiation of templates

* C99 long long type and its unsigned counterpart

* C99 __func__ predefined identifier

* constexpr, a generalized mechanism for treating a function calls as constants

* template aliases: a generalized typedef facility that can be used for templates

* Operator decltype for querying the type of an expression


extern templates(不要与exported templates混肴)一种限制模板隐式实例化的机制。

*C99 long long类型和它的unsigned类型。





At this stage, it isn't clear yet whether all of these proposals will make it into the next standard. While there is a clear intention to do so, the voting on the Final Candidate Document must take place before the end of 2007 to comply with ISO rules. This leaves the committee two more meetings (in April and October 2007) to finalize the list of C++09 features. C++09 is much closer than it seems!

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页