Я создал еще один пример, который отвечает на вопрос:
#include <vector>
#include <iostream>
struct a
{
a() { std::cout<<"constructor" << std::endl; }
a(const a&) { std::cout<<"copy constructor" << std::endl; }
a(a&&) { std::cout<<"move constructor" << std::endl; }
operator int(){return 0;}
};
int main()
{
std::vector< a > v = { a(), a(), a() };
std::cout<<"loop start" << std::endl;
for ( auto it : v )
{
std::cout<< static_cast<int>(it)<<std::endl;
}
std::cout<<"loop end" << std::endl;
}
Очевидно, что auto
расширяется до int
, и копия создается. Чтобы предотвратить копирование, цикл for должен иметь ссылку:
for ( auto & it : v )