Suppressing lint message lnt-accidental-copy 'auto' doesn't deduce references

Viewed 228

In Visual Studio 2019 16.11.4, the following code gives me this lint message for the for() statement:

lnt-accidental-copy 'auto' doesn't deduce references. A possibly unintended copy is being made.

(This is a made up example, simplified from real code. I'm not really just printing a list of odd numbers.)

#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>

using namespace std;

class SomeClass
{
  public:
    int i;
};

void SomeMethod(vector<SomeClass> vectorOfStuff)
{
    auto partIt = partition(begin(vectorOfStuff), end(vectorOfStuff), [](auto& x) {
        return (x.i & 1) == 0;
    });
    for (auto it = partIt; it != end(vectorOfStuff); ++it)
    {
        cout << "doing something with " << it->i << endl;
    }
    vectorOfStuff.erase(partIt, end(vectorOfStuff));
}

The suggested fix is to change the auto it = partIt to auto &it = partIt. Normally that is good advice, but in this case, I want to keep partIt unchanged for the call to erase() so I want a copy, not a reference.

According to the announcement for the linter:

Configuration: currently the feature is either enabled or disabled. There isn’t a way in the current version to enable/disable or change the severity of individual checks.

And I haven't found anything more recent about suppression.

One fix that I have come up with is to change the auto it = partIt to auto it = next(partIt, 0). Another is to spell it out as vector<SomeClass>::iterator it = partIt. But those both look a touch clunky, and I'll have to add a comment to to explain I'm working around a lint message.

Is there a cleaner way to say "yes, I really want a copy of the iterator"? Or have I missed how to suppress the message in this instance?

0 Answers
Related