Channels ▼
RSS

C/C++

4 Useful New Features in C++0x


Extracting Type Information

The auto specifier is useful for initializing variables when we define them, but we sometimes define variables without initializing them. For example, a variable might be part of a data structure:

             struct When {
                 ??? date;       // What types do we put here?
                 ??? time;
             };

In this case, we can't use auto to say that date and time have the same types as whatever get_date and get_time return, because we don't have initializer expressions to supply types for date and time. Instead, we can write:

     struct When {
         decltype(get_date()) date;
         decltype(get_time()) time;
     };

The idea is that if e is an expression, decltype(e) is the type that e would have if it were evaluated — even though the expression is not actually evaluated. As a result, the data members date and time get the types of get_date() and get_time(), respectively, and the author of When is spared having to look up those types' names.

As with auto, we expect that decltype will be widely used to make everyday programs easier to write.

Initializing Variables' Contents

The usual way to construct an object in C++ is to supply arguments to its constructor. Sometimes these arguments are data for the object to store:

string hello("Hello, world!");    // hello contains Hello, world!

and sometimes the object uses the constructor arguments in ways other than storing them directly:

vector<string> strings(42);     // strings contains 42 empty strings

A common early mistake among C++ programmers was to supply an argument that a constructor interpreted differently from what was intended:

     double average(const vector<int>&);
  … average(42) …                    // Takes the average of a 42-element vector of zeroes!

Such mistakes came about because there was no convenient way to initialize a container from a series of element values:

  vector<int> primes;
  primes.push_back(2);    // Put the first few prime numbers into the vector
  primes.push_back(3);
  primes.push_back(5);

A programmer who wished to define a vector that started with three specific values didn't really have an easier way to do so.

C++98 let us avoid mistakes such as our call to average above by introducing explicit constructors. An explicit constructor can be called only as part of explicitly constructing an object of a known type. The C++98 standard vector constructor that expects a size is explicit, so average(42) does not compile. A programmer who really wants to construct a 42-element vector of zeroes can still do so by calling average(vector<int>(42)).

C++0x makes it easier to initialize a container's elements by letting us use curly braces whenever we initialize an object. The values in the curly braces can be arguments to an ordinary constructor. More usefully for this example, classes can also define constructors that take a sequence of values. All the values must have the same type, but the number of values we can supply is not fixed. Classes such as vector can use this new kind of constructor to let us supply a sequence of element values. For example:

 vector<int> primes{2, 3, 5};    // three elements, values 2, 3, 5
 vector<int> small{1000};        // one element, value 1000
 vector<int> large(1000);        // 1,000 elements, all with value 0

Like vector, each of the C++0X library containers defines a constructor that lets us provide a sequence of initial element values.

This description only scratches the surface: The rules for initialization and constructors have always been both important and complicated. Although we think that the effort to make initialization more uniform will make life easier for users of class libraries, it will sometimes do so at the expense of increasing the burden on library designers. This tradeoff is probably for the good, because there are many more library users than there are designers. (At least, we hope there are.)

By letting programmers use curly braces to initialize class objects, C++0x makes library containers look even more like the built-in types. In doing so, C++0x also makes it possible for programmers to say whether a constructor argument controls a container parameter such as its size, or whether the argument is intended to be stored in the container.

Summary

The C++03 standard was not quite 800 pages long; the C++0x standard will be more than 1,300 pages. It would be absurd for us to try to discuss every new idea in C++0x, and even more absurd for us to expect you to read such a discussion. However, most C++ programmers will not care about many of the additions to the C++0x standard. Accordingly, this article has talked about four C++0x features that we think you'll care about: auto, range for, decltype, and brace initialization.

Our next article discusses how C++0x makes its standard libraries easier and more efficient to use. Our final article will discuss how C++0x makes life easier for library authors as well.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video