sparrowwf
2019-04-09 23:21
采纳率: 100%
浏览 648

C++ for循环遍历, 遍历加和不加&,为何结果差异这么大:for (auto p : ps) 与for (auto &p : ps)

问题:
见下面的代码和结果
1.加过地址打印,两种方式打印的地址全部完全相同,猜测是for遍历中始终使用一个临时中间遍历
2.不加引用符表征的是复制操作,更改不会同步;加了是别名引用,更改会同步?
3.如果2猜测是对的.那么&(p.name)地址值应该不一样.然后结果还是一样
4.那么该如何解释背后原理?

代码:
#include
#include
#include
#include "fact.h"
using namespace std;

class People {
public:
string name;
People(string n) {
name = n;
}
};

int main(int argc, char** argv) {
cout << "main test start" << endl;
vector ps;
ps.push_back(People("zhangshan"));
ps.push_back(People("lisi"));
ps.push_back(People("wangwu"));

for (auto p : ps){
    p.name += "123";
}
for (const auto p : ps){
    cout << p.name << endl;
}
cout << "================" << endl;
for (auto &p : ps){
    p.name += "123";
}
for (const auto p : ps){
    cout << p.name << endl;
}   
return 0;

}
结果:
#include
#include
#include
#include "fact.h"
using namespace std;

class People {
public:
string name;
People(string n) {
name = n;
}
};

int main(int argc, char** argv) {
cout << "main test start" << endl;
vector ps;
ps.push_back(People("zhangshan"));
ps.push_back(People("lisi"));
ps.push_back(People("wangwu"));

for (auto p : ps){
    p.name += "123";
}
for (const auto p : ps){
    cout << p.name << endl;
}
cout << "================" << endl;
for (auto &p : ps){
    p.name += "123";
}
for (const auto p : ps){
    cout << p.name << endl;
}   
return 0;

}

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • sparrowwf 2019-04-09 23:24
    最佳回答

    抱歉,如上猜测.是log打印加错地方了.
    int main(int argc, char** argv) {
    cout << "main test start" << endl;
    vector ps;
    ps.push_back(People("zhangshan"));
    ps.push_back(People("lisi"));
    ps.push_back(People("wangwu"));

    for (auto p : ps){
        p.name += "123";
        cout << &(p.name) << endl;
    }
    for (const auto p : ps){
        cout << p.name << endl;
    }
    cout << "================" << endl;
    for (auto &p : ps){
        p.name += "123";
        cout << &(p.name) << endl;
    }
    for (const auto p : ps){
        cout << p.name << endl;
    }   
    return 0;
    

    }

    int main(int argc, char** argv) {
    cout << "main test start" << endl;
    vector ps;
    ps.push_back(People("zhangshan"));
    ps.push_back(People("lisi"));
    ps.push_back(People("wangwu"));

    for (auto p : ps){
        p.name += "123";
        cout << &(p.name) << endl;
    }
    for (const auto p : ps){
        cout << p.name << endl;
    }
    cout << "================" << endl;
    for (auto &p : ps){
        p.name += "123";
        cout << &(p.name) << endl;
    }
    for (const auto p : ps){
        cout << p.name << endl;
    }   
    return 0;
    

    }

    已采纳该答案
    评论
    解决 无用
    打赏 举报