2017-02-04 4 views
0

"&"を使用する必要がある場合としない場合は、
たとえば、両方のループで同じ結果が得られます。"&"を自動で使用する

std::vector< Product* > itemByColor = pF.by_color(vecProds, Color::Red); 

for(auto i : itemByColor) 
{ 
    std::cout << " product name <<" << i->name<< std::endl; 
} 

あなたがstd::stringまたは(conststd::string&を入力することを決定したかどうかと同じ

for(auto& i : itemByColor) 
{ 
    std::cout << " product name <<" << i->name<< std::endl; 
} 
+0

、コピーとsp2danny @参照 – sp2danny

+0

の間に大きな違いがあってはならない。そのような 'int'sなど小さめのオブジェクトについては、リファレンスを服用することは、実際に低下することがありますパフォーマンス。 – 3442

答えて

0

多かれ少なかれ。つまり、オブジェクトをコピーするか、オブジェクトを参照するかどうかです。限り、あなたは唯一* *値を読み込むよう

std::vector<int> my_vector{ 1, 2, 3, 4, 5 }; 

int copy = my_vector[ 0 ]; 
int& reference = my_vector[ 0 ]; 

++copy; 
std::cerr << my_vector[ 0 ] << '\n'; // Outputs '1', since the copy was incremented, not the original object itself 

++reference; 
std::cerr << my_vector[ 0 ] << '\n'; // Outputs '2', since a reference to the original object was incremented 

// For each 'n' in 'my_vector', taken as a copy 
for(auto n : my_vector) 
{ 
    // The copy ('n') is modified, but the original remains unaffected 
    n = 123; 
} 

// For each 'n' in 'my_vector', taken as a reference 
for(auto& n : my_vector) 
{ 
    // The original is incremented by 42, since 'n' is a reference to it 
    n += 42; 
} 

// At this point, 'my_vector' contains '{ 44, 44, 45, 46, 47 }' 
関連する問題