Tagged as

C++11 – A Glance [part 1 of n]

A glance at the C++11 Standard, covering features supported in VS2010.

Introduction

C++0x is now a formal standard and will hereafter be called as C++11. It is ratified by ISO C++ in the year 2011.The purpose of this article is to give a bird's eye of most of the C++11 features and for those features which are already shipped into VS2010 a deep analysis is given. This article can serve as a platform to start comprehensive study on individual features.

The article is divided into parts so that the length is at bay. I myself will get scared to read a lengthy stuff. Moreover it will be boring to grab every thing in one sitting.

As this is my first article in codeproject, please bear with the formatting and with the typos if any.

Background

It took almost a century for Charles Babbage's Difference Engine to evolve into a electrically powered computer. In the 1940s, only assembly level languages are used owing to the then computer's low speed and memory capacity. Things started to turn after a decade and the period between 1950 to 1970 saw blooming of many programming languages of which many survived till date.In 1979 Bjarne Stroustrup working for the Bell labs began enhancing the "C" language first adding classes, then virtual functions, operator overloading, multiple inheritance, templates, and exception handling among other features. He called it initially "C with Classes". It was renamed to C++ [++ may be to say that it increments C] in the year 1983.

C++ Landmarks/Iterations time line:

1983 - First commercial C++ compiler1998 - C++ standards committee standardized C++ [C++98]2003 - A bug patch with no new features [C++03]2005 - A technical report called “Library Technical Report” (TR1 for short) was released2011 - Introduced significant number of features and also enhanced C++ standard library.

As we can see that this iteration is the biggest one ( ok..ok...STL addition may also be big).

Do we have to know this new Standard ??

YES .The sooner the better. Resisting change is human. But we programmers/developers will be out of job the day when every language or project reaches static phase. We like to be in dynamic projects and the same is with language.Change is inevitable and when an expert committee brainstormed for almost a decade then the result will obviously be beautiful and fruitful.

Even if we are not interested in incorporating these new iterations in the code, a quick glance on the features will help us to avoid or even think before coding certain scenarios using old compilers. Moreover by just switching to a compiler supporting C++11 we will be immensely benefited as the Standard template library is enhanced and revamped for performance. So if your project is using STL contianers/algorithms, then switch as early as possible.

C++11 Features

Here is a table summarizing core C++11 features and also their implementation status in VS2010

Individual Features

This feature is introduced in a effort to make C++ a more usable language. The committee have given a new meaning for the 'auto' keyword [just to remind the readers that the old auto keyword is used to declare a variable having local scope and all local variables if their storage class is not specified as static, extern or register are implicitly converted to auto storage-class specifier].

As per the new interpretation, auto helps in deducing the type of the defined object by inspecting the RHS expression or it's initializer.

auto i = 5// i will be of type int
int n=3;
double pi=3.14;
auto j=pi*n; // j will be of type double

Now let's take a case where the type is hard to write

// take a hypothetical Map of ( int and an map(int,int) )
map< int, map<int,int> > _Map;
// see the verbose for defining a const iterator of this map
map<int, map<int,int>>::const_iterator itr1 = _Map.begin();
// now with auto our life gets simplified
constauto itr2 = _Map.begin();

Now take a case where the type is hard to know

template<class U, class V>
void Somefunction(U u, V v)
{
??? result = u*v; // now what would be the type of result ???
// with auto we leave the compiler to determine the type
auto result = u*v;
}

I will be extending this function for the next feature to know more usability of auto. The auto keyword finds more usage while declaring and initializing a variable to a lambda expression [we will cover lambdas soon].

Few points on this feature:

1. we can use const, volatile, pointer(*), reference (&), rvalue reference (&& - we will know about this shortly) specifiers on auto keyword

return_value decltype( expression )[ return_value is the type of the expression parameter ]

This can be used to determine the type of a expression. As hinted by Bjarne, if we just need the type for a variable that we are about to initialize auto is often a simpler choice. But if we need a type for something that is not a variable, such as a return type then decltype is the thing we should be trying.

Now lets look back an example we worked earlier,

template<class U, class V>
void Somefunction(U u, V v)
{
result = u*v; // now what would be the type of result ???
decltype(u*v) result = u*v; // Hmm ....we got what we want
}

In the next section I will make you familiar with the notion of combining auto and decltype to declare template functions whose return value type depends on its template arguments.

Few points on decltype:

1. If the expression is a function, then decltype gives the type of the return of the function

2. If the expression is an lvalue then decltype gives lvalue reference to the type of the expression.

struct M { double x; };
double pi = 3.14;
const M* m = new M();
decltype( (m->x) ) piRef = pi;
// Note: Due to the inner bracets the inner statement is evaluated as expression,
// rather than member 'x' and as type of x is double and as this is lvale
// the return of declspec is double& and as 'm' is a const pointer
// the return is actually const double&.
// So the type of piRef is const double&

3. It is important to note that decltype does not evaluate the expression as auto does but just deduces the type of the expression

int foo(){}
decltype( foo() ) x; // x is an int and note that
// foo() is not actually called at runtime

This is completely a new feature for C++ developers. Till now the return value of a function should go before the function's name. From C++11, we can also put the return type at the end of the function declaration, of course only after substituting auto for the name of the return type. Now why we want to do this. Let's find out:

This is an error with earlier compilers as there is no space between >'s and the compiler will treat it as right shift operator.But C++11 compilers will parse these multiple right angle brackets as closing to the template argument list and saves us from need of putting space between > .This is not a great feature when compared to the rest, but as we c++ developers look for perfection, here is the one that is taken care of.

This macro can be used to detect and diagnose compile-time errors. Compile-time period. This is in contrast to the CRT-assert macro which an assertion at run-time. This goody can be used to check program invariants at compile-time.

This takes an expression that can be evaluated to bool and an string literal. If the expression evaluates to false, then the compiler issues an error containing the specified string literal and the compilation is failed. If true the declaration has no effect.

The static_assert declaration is especially useful for debugging templates. The compiler evaluates the constant-expression parameter immediately if it does not depend on a template parameter. Otherwise, the compiler evaluates the constant-expression parameter when the template is instantiated.

This feature is introduced mainly to take care of the pitfalls generated by using the (infamous and nasty) NULL macro. As we all know that NULL is nothing but a preprocessor expanding to 0 at compile time and this expansion often leads to ambiguity. Take for case,

void SomeFunction(int i){ }
void SomeFunction(char* ch) { }

now a call like : SomeFunction(NULL) will always be resolved to SomeFunction(int i), even though we want to call SomeFunction(char* ch) with null pointer argument.To force we have to call like: SomeFunction( (char*) NULL ) // yak ..uglyTo avoid these inconveniences the nullptr is introduced finally. The nullptr literally means null pointer is not an integer. This can thus be safely used to indicate that an object handle, interior pointer, or native pointer type does not point to an object.

Very nice and useful, thank you!
But can you please give some more examples for 'decltype'?
In particular, how can one determine the type of the function "add" - not for its result - for "int add(int i, int j) { return i j; }"?
And how can one determine the type of "x" in "struct M { double x; };"?
Please explain the differences in usage of 'decltype' and its arguments in these cases.

All the features were already explained in a nice and much more correct way even on the wikipedia. How comes that so many devs come up with their own idea every now in a while ? (not saying you copied stuff though)

At least you should have added comparison of supported features for three main compilers on the market, not just Visual Studio.

I am really puzzled. In last months I saw a lot of articles on CP that are like chapters or lectures on and from courses on C++ 101, 201, etc. I can't get what is new in these articles: method of teaching, examples, something else. Can you explain why you decided to write this article and why it is better than info from other sources. I just want to understand, you know.

When something is new, obviously there will be people interested to explain them in simple terms and with less words to others what they understand from spending hours and by scrolling many pages and documents.

For example, there are n number of examples from basics to advanced concepts regarding Windows Phone 7 at MS site. Why to flood CP with all these things? It's just a different perspective and some may catch up with this way of presentation.

First, thank you for reply.
For me, each article no matter where published should add something new to the subject.
Your article is well written. For me the table of the features implemented in VC++ 10 is very valuable, and I do not remember somebody else have published it.
It is my wish, that given the other authors already wrote about new features in C++ 11 standard, to have more info about why the feature was included in the standard (motivation), pro and contra to use it (think about tuples) would not hurt. (In some places this info is presented.) This info is spread over Internet, but if you gather it in one place, in your article, it would be very great. Again, it is only the wish, we can't judge the article based on what is not in it. But if you are thinking about next version...

What is not there in Wiki? From babysitting to bomb making all is there. And I personally like to read general info for Wiki.

Coming to our field, regarding OOPS & C++ almost 90% concepts are elaborated with much detail (some are more clear that what we find in “The Design and Evolution of C++” by Stoustrup ) !!!!!. And coming to C# there is much better info than what you get in MSDN

A C++11 standard, voted by the committee is available as a doc at one of the reference I mentioned. It's better to read and understand from there (if you have time and patience), why to even go to Wiki or to any sites/ blogs !!!!.

And coming to “Originality”, How can an article explaining/introducing a framework (like MFC) or technology (like COM) be original or C++11 in this case? I have to obviously lift some details from the original draft. Should I not?

I myself started understanding COM by starting with Aria Ansari's article (COM from scratch) in CP. And really loved and adored “An Idiot's Guide to C++ Templates - Part 1 by Ajay Vijayvargiya.
Hey... he is explaining templates which came to existence some 12 years ago – Is this also trivial ? No not at all .....it is just another view, another way and another style of presentation.

And coming to comparison of compilers, I have familiarity mostly with VC++ and I feel that I am not the right person to do this. I like somebody doing it.

After checking all these type of messages, I am thinking of refraining myself in updating the rest of the features. It's better to grab them from the draft or from WIKI. Why to waste my time in presenting and formatting for CP.

I hate long replies, but I have to in this case.

Thanks any way for glancing this article and hope I have convinced you.

Hi. You mean that there is difference between the (acceptable) maximum function names between the two iterations? I am not aware of it. In fact the maximum length of function names I ever used never crossed 15, so I really did not bothered about it. Do we have to?