Skip to content

Request: Scan code for dangerous uses of "auto" #196

@KenBirman

Description

@KenBirman

I ran into a bug in my own C++ code that got me thinking about whether we might have the same issue anywhere in Derecho or Cascade. I think we should quickly do a visual scan of our code.

The issue: suppose you have a std::vector or some other C++ STL type that offers an indexed getter but has a structure under the covers. Now consider these three lines:

std::vector<int> my_vec {11111, 22222, 33333}; auto item = my_vec[1]; ++item;

Compare with these three:

std::vector<int> my_vec {11111, 22222, 33333}; int item = my_vec[1]; ++item;

At a glance you would expect them to be the same. In the "auto" case you might assume that item is going to be of type int and that this code is the same as if you explicitly declared it to be an int. But in fact you would be wrong! The indexed getter is a const method that returns an lvalue reference, template-expanded by the std::vector class, and this can be constexpr evaluated statically. So, at compile time, the auto-declared item becomes a reference to the underlying element of the original vector. When you increment item, the contents of my_vec[1] will change, even though the code is written as if item was a separate copy of that vector element!

This bug seems to be fundamental to the way that C++ 17 is aggressively auto-expanding and constexpr-evaluating code these days. When you think about it, the approach makes sense -- but unless someone anticipated this when building the STL and used the && postfix operator to explicitly make this index operator an rvalue-only type, we won't get an error and we will get the wrong behavior.

So, I think we should code-review Derecho and Cascade to ensure that we don't have any errors of this form in our code.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions