此代码在函数内将新对象添加到静态列表。该列表通过引用传递给该函数。
列表中新对象的生命周期是什么?
代码示例:
#include <list>
#include <string>
#include <iostream>
using namespace std;
struct MyStruct
{
int x;
string str;
};
void addStructToList(list<MyStruct> &myStructlist, int _x, string _str)
{
MyStruct newStruct;
newStruct.x = _x;
newStruct.str = _str;
myStructlist.push_back(newStruct);
}
void main()
{
list<MyStruct> myStructlist;
addStructToList(myStructlist, 111, "aaa");
addStructToList(myStructlist, 222, "bbb");
addStructToList(myStructlist, 333, "ccc");
for (auto it = myStructlist.begin(); it != myStructlist.end(); it++)
{
cout << it->x << " " << it->str << endl;
}
system("pause");
}
输出:
111 aaa
222 bbb
333 ccc
Press any key to continue . . .
问题:
这段代码在内存使用方面安全吗?
什么是“newStruct”生命周期?addStructToList() 还是 Main() ?