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() ?
Is this code safe in terms of memory usage?
Yes it is safe. list
und string
take care of memory management automatically. You may get an out of memory error if you would add really many items to your list (like 100000000).
What is "newStruct" lifetime? addStructToList() or Main() ?
newStruct
only exists in the function addStructToList
. But a copy is created and put into myStructlist
. The copy lives on in Main
.
Small additional remark: Always pass string
by const reference and not by value:
void addStructToList(list<MyStruct> &myStructlist, int _x, const string& _str) { ... }
Another remark: You use the word "static" misleadingly. See The static keyword and its various uses in C++ for explanation what static means in C++.