一个引用没效果错误示范
#include <iostream> #include <unordered_map> using namespace std; class TestClass { public: std::unordered_map<int, int>& GetData() { return m_data; } private: std::unordered_map<int, int> m_data; }; int main() { TestClass instance; { auto map = instance.GetData(); //引用错误示范, 这边的等号左边map是对右边的复制, 后面添加数据在临时对象上面操作的 //auto& map = instance.GetData(); //正确用法 map.insert(std::make_pair(1, 1)); } { auto map = instance.GetData(); int size = map.size(); cout << "map's size is :" << size << endl; //输出:map's size is :0 } system("pause"); return 0; }