2017-02-04 38 views
0

當我們需要使用「&」時什麼時候不用?例如下面的
,兩個for循環產生相同的結果。使用「&」加自動

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

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

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

只要你只*閱讀*的價值,不應該有一個副本,並@ sp2danny參考 – sp2danny

+0

太大的區別:對於短小的對象,如'int's,採取參考實際上可以降低性能。 – 3442

回答

0

或多或少一樣的,你是否會決定鍵入std::string或(conststd::string&。也就是說,無論您想要複製對象還是對其進行引用。

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 }'