Dynamic Memory Allocation and STL
On Jun 20, 3:19 pm, Markus Pitha <newsgroupsNOS...@pithax.net> wrote:
Zachary Turner wrote:
I know this isn't your question, but you know that C++ already comes
with a linked list right? And also, it may have been better style to
declare your list on the stack instead of as a pointer and then using
new / delete.
Where can I find this linked list? In the internet, I only find
tutorials how to create a linked list.
Which benefits does it have to create it on the stack?
I thought that dynamically allocated space would be better.
#include <list>
using namespace std;
int main()
{
list<int> mylist;
mylist.push_back(1);
mylist.push_back(2);
mylist.push_back(3);
}
If you take this approach, there is a bit of a learning curve you will
have to overcome. Some keywords you can use to search for related
topics are:
STL (Standard Template Library) - a collection of generic containers
and algorithms provided with C++)
std::list - One of the generic collections in the STL. It's a doubly
linked list, and supports any time
iterator - The STL paradigm for iterating over any and all collections
in the STL.
Regarding memory allocation, stack based and heap based memory
allocation is totally separate.
Heap based - You specify exactly when it is created (with new), NULL
value is possible, and you specify exactly when it is deleted (with
delete)
Stack based - It is created the instant it is declared, NULL is not
possible, it is deleted immediately when it goes out of scope.
Consider this code:
if (true)
{
list<int>* pList = new list<int>();
pList->push_back(1);
delete pList;
}
Here you create a new instance of list immediately when you declare
it. You never make use of the null value, and you delete it
immediately before it goes out of scope. This is equivalent to what
stack based allocation provides. Therefore, the code is equivalent
to:
if (true)
{
list<int> list;
list.push_back(1);
}