如下所示代码:
std::string foo = "foo-string";
std::string bar = "bar-string";
std::vector<std::string> myvector;
myvector.push_back (foo); // copies
myvector.push_back (bar); // moves
std::cout << "myvector contains:";
for (std::string& x:myvector) std::cout << ' ' << x;
std::cout << '\n';
for语句:for (std::string& x:myvector)替换成for (std::string x:myvector)好像对结果没什么影响,这儿的引用符号有什么特殊作用吗?
for循环里std::string& x,这里的x是引用,直接用vector里的对象打印。其实这里不需要修改vector里的对象,可以用const std::string& x。
如果不用引用for循环里std::string x,则每循环一次用copy constructor拷贝一个string对象,打印完后扔掉,会有额外开销。所以好的做法是用引用。
说明x是vector里的元素的引用,一是避免在给x赋值的时候发生拷贝,二是便于修改vector的内容。
如有帮助,请采纳一下,谢谢。