3 ms·
This is true, though there are still real risks in just using auto everywhere. For one thing, duck typing is always vulnerable to code that is syntactically co
by Silhouette 12y ago
This is true, though there are still real risks in just using auto everywhere.
For one thing, duck typing is always vulnerable to code that is syntactically correct but semantically nonsense. For example,
employee.fire()
and
nuclear_missile.fire()
have quite different meanings, but if all you write is
auto x = get_an_x()
x.fire()
then nothing in the language or compiler will stop you or notice the changed implication in this scenario.
C++ is also vulnerable to a slightly more sinister variation because many conversions can be made implicitly, and sometimes those conversions are lossy. For example, suppose x was converted from an integral value to a floating point one because get_an_x needed was upgraded to offer more precision. Unfortunately, all the code you've got that later compares x to a known value using == might now be broken (comparing floating point values without a suitable tolerance) and again depending on how you've got your compiler's warnings set up you might never notice.
If C++ had a stronger type system, then at least the latter issue would be less dangerous, but with the language we're talking about today I think over-use of auto is a risk that shouldn't be ignored in code reviews.
- thebear 12y agoNice example with the nuclear missile. For those to whom this seems contrived, let me explain why the issue of type-safety and semantics is so important to me. I used to work in symbolic computation. In that world, it is very common for a large number of types to have the exact same operations, although they are semantically very different. Example: groups. If type-safety is a purely syntactical notion, then type is no longer a tool to enforce the distinction between different kinds of groups, such as abelian groups, torsion-free groups, etc.