this code adds a new object to a static list, within a function. the list is passed by reference to the function.
what in the lifetime of the new object in the list?
code sample:
#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");
}
output:
111 aaa
222 bbb
333 ccc
Press any key to continue . . .
Question:
Is this code safe in terms of memory usage?
What is "newStruct" lifetime? addStructToList() or Main() ?