C++:RangeBasedFor
lastmod 2016-07-23created 2015-03-195 edits
Example
auto warning
There is something to watch out for when using auto. First, look at the example below.
#include <iostream>
#include <vector>
#include <type_traits>
struct Temp
{
Temp() {
std::cout << "DEFAULT\n";
}
Temp(Temp const & obj) {
std::cout << "COPY\n";
}
Temp(Temp && obj) {
std::cout << "MOVE\n";
}
~Temp() {
std::cout << "REMOVE\n";
}
Temp & operator=(Temp const & obj) {
std::cout << "COPY =\n";
return *this;
}
Temp & operator=(Temp && obj) {
std::cout << "MOVE =\n";
return *this;
}
};
int main()
{
std::vector<Temp> test(1);
std::cout << "START FOR\n";
for (auto cursor : test) {
std::cout << "IS_REFERENCE: " << std::is_reference<decltype(cursor)>::value << std::endl;
std::cout << "IS_RVALUE_REFERENCE: " << std::is_rvalue_reference<decltype(cursor)>::value << std::endl;
}
std::cout << "END FOR\n";
return 0;
}
OUTPUT:
In the case above, the auto variable in the for statement is an lvalue, so the copy operator is invoked. Therefore, loop by reference, as in for (auto & cursor : test). After changing the code and compiling, the result is as follows.