The effect of auto on compile time

The auto keyword of C++11 is far less heavyweight than templates - its compile-time "overhead" is comparable to that of sizeof, which means it's close to zero.

Unlike templates where the compiler needs to perform sizeable amount of computation during the expansion (the template language in C++ is Turing-complete), the auto keyword requires the compiler to figure out the type of an expression, which is something the compiler knows anyway. In fact, it would have to figure out the type of the expression even without the auto keyword to decide if type conversions need to be applied.


What most people mean by "template bloat" is a myth. A template instantiated twice produces no more code than two separate functions that handle those same types. If you instantiate the template thousands of times you'll get lots of code, but if you write thousands of functions you'll get the same amount of code (see Diet Templates for some genuine ways carelessly defining templates can lead to some "bloat".) Templates can affect compilation time, but that is not "bloat".

The auto keyword is not a template, it uses the same rules of type deduction as templates, but if you write auto i = 1; there is only one "instantiation" i.e. the auto only has to deduce one type, and it produces exactly the same code as int i = 1; so there can't be any bloat. It's just alternative syntax for declaring a variable. Zero bloat.

Now polymorphic lambdas are different, they define a type with a member function template operator(), so each time you call the closure's operator() with different argument types you will instantiate another specialization of the function template, but that has nothing to do with auto, the use of auto is just syntax for declaring a template. If you call it thousands of times you'll get lots of code generated but no more than if you used thousands of different lambda expressions for the specific types you use (you almost certainly get less code with the generic lambda, because there's only one closure type so less RTTI and type names for the compiler to create and store in memory.)

Tags:

C++

C++14