Modern C++ and backwards compatibility for keyword auto

With the introduction of keyword auto to implement type deduction, ever wonder why this “new” keyword didn’t break tons of old code when projects were migrated to newer compilers? Turns out keyword auto has been reserved for quite some time in the standard. Therefore it isn’t a new keyword at all, but one which was rarely used. The standard addresses this in the appendix sections and . These sections state that auto can no longer be used as a storage class specifier. The rationale given for this change, is basically that the keyword is being re-purposed for better use.

What was the original use of auto? It was to be used to define automatic storage duration of local variable within a block. The block could be a function or just a block of code. This means the local variables are created in the block, and cease to exist at the end of the block. For example:

 // Example 1
{
   // Automatic storage duration by default.
   int myVar = 0;
   …
   // Not valid code starting with C++11.
   auto int otherVar = 0; 

} // Both vars cease to exist.

Or, more interestingly:

// Example 2
std::mutex myMutex;
{
   // Automatic storage duration. 
   std::lock_guard<std::mutex> myLockGuard(myMutex);
   ...
   
} // variable  ceases to exist and  mutex is released.

As shown in the example 2 above, this automatic storage duration is a key part of RAII . The other types of storage being register, static, extern, thread_local. The fact that auto storage class is the default, doesn’t make it particularly useful. Therefore, it’s easy to see why having a name like “auto” it was recycled to it’s new purpose.

Leave a Reply

Your email address will not be published. Required fields are marked *