Quantcast
Channel: Bartek's coding blog
Viewing all articles
Browse latest Browse all 325

Auto keyword in Cpp11

$
0
0
auto i = 0;
C++11 brings us very useful set of tools. They add a fresh air to the hard life of a programmer. The updated syntax makes the language a bit more modern.
Let us look at a nice keyword 'auto' that at first sight might seem very simple. It appears that there are still some 'features' behind it and worth to consider. For instance what about references and pointers?
Auto is very useful in situations like:
std::vector<std::string> cityList = {"Warsaw", "Cracow"};
for (std::vector<std::string>::const_iterator it =
cityList.begin();
it != cityList.end();
++it)
{
std::cout << *it << std::endl;
}
Now it is better to write:
for (auto it = cityList.cbegin(); it != cityList.cend(); ++it)
std::cout << *it << std::endl;

// or even:
for (auto const &city : cityList)
std::cout << city << std::endl;
Variable declared with auto is deduced at compile time and, that way, it saves a lot of typing from our side. It will be often used with complex template expressions and STL types. Cool feature... but?

The questions

But what about more complicated types... what about pointers and references and their constness?
double var = 10.0;
double &varRef = var;
auto varAuto = varRef;
varAuto will have double (not reference to double) type!.
double var = 10.0;
double *varPtr = &var;
auto varAuto = varPtr;
This time though varAuto is pointer to double. Why is there a difference then?
From C++11 spec [pdf] 3335 - C++11 spec, 7.1.6.4): Auto is deduced almost the same as when declaring a template function
template <class U> void f(U u);
As we see it will work for the normal types and pointers, but for references and const references we need to explicitly write &U or const &U. Otherwise reference or constness will be lost. Maybe this will help us to remember how auto actually works. Some more examples below:
const float myFloat = 0.0f;
auto f = myFloat; // f is 'float', const is dropped!
f = 2.0f; // fine :)

const auto fc = myFloat; // fc is const float of course
fc = 2.0f; // error!
int b = 10;
const int *pb = &b;
auto ppb = pb; // type is const int*
*pb = 100; // error!
*ppb = 101; // error!
int b = 10;
int *const pb = &b;
auto ppb = pb; // type is int*
*pb = 100; // ok of course
*ppb = 101; // ok of course
// maybe it is better to explicitly use '*' when
// declaring a pointer. It will be more visible.
int b = 10;
auto *pba = &b; // same type
auto pbaa = &b; // same type
TODO: upgrade those examples and explain those questions better!

Other things

  • Decltype is keyword 'connected' with auto. See some more information here and here
  • Before C++11 auto keyword was used to declare a variable with a local lifetime. Now such declaration generates error (see this msdn link). How about Gcc?

Links


    Viewing all articles
    Browse latest Browse all 325

    Trending Articles