2

I was trying to make a range based lopp like this in C++11:

std::vector<Satellite> Satellites; // Class member
//...

int number = 1;
for(auto sat : this->Satellites) {
    sat.setNumber(number++);
}

And I'm getting this warning:

'auto' changes meaning in C++11; please remove it [-Wc++0x-compat]

Of course I could stick to for(Satellite sat : this->Satellites), but I was trying to test the auto keyword.

I had read that usage of auto was possible with C++11, but recently I found that it changed since C++0x (or it looks like it did!):

The keyword auto isn’t new; it actually dates back the pre-ANSI C era. However, C++11 has changed its meaning; auto no longer designates an object with automatic storage type. Rather, it declares an object whose type is deducible from its initializer. The old meaning of auto was removed from C++11 to avoid confusion.

So: Am I able to use it like this with C++11 and my problem is at the IDE (Eclipse CDT Juno), or should I use it in a different way (or remove the auto keyword at all)?

Sean
  • 60,939
  • 11
  • 97
  • 136
Roman Rdgz
  • 12,836
  • 41
  • 131
  • 207

2 Answers2

5

Your usage is "fine" in C++11, and is invalid syntax in C++03.

The only potential problem is that you are making a copy of each Satellite, which is not necessarily what you want. You may get a reference like this:

for(const auto& sat : this->Satellites) { ....

or

for(auto& sat : this->Satellites) { ....

if you want mutable references to the vector's elements.

You should check whether your compiler fully supports this feature. Whereas it is valid C++11, the warning suggests and old pre-C++11 standard compiler.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Thanks for the advice avoiding copies! I have cpp 4.8.1, so I think my compiler version is fine. So the problem must be at the Makefile (if CDT Juno still uses it, because I don't know for sure: I had to add every src folder into project properties, which wasn't necessary in older CDT version). Maybe I'm missing some flag at the project properties? – Roman Rdgz Jan 21 '14 at 09:41
  • 1
    Aaaaand, sure I was: http://stackoverflow.com/questions/17457069/enabling-c11-in-eclipse-juno-kepler-cdt – Roman Rdgz Jan 21 '14 at 09:46
0

You were compiling with a non'11 compiler, that's why you got the message.

Andor
  • 1