Skip to content
Search

C++:RangeBasedFor

lastmod 2016-07-23created 2015-03-195 edits

Example

for (int i : m_Table) { // 테이블 내의 int 형 전부 다 돌음
    std::cout << i << " ";
}

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:

DEFAULT
START FOR
COPY
IS_REFERENCE: 0
IS_RVALUE_REFERENCE: 0
REMOVE
END FOR
REMOVE

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.

DEFAULT
START FOR
IS_REFERENCE: 1
IS_RVALUE_REFERENCE: 0
END FOR
REMOVE

Favorite site