STL list problems

G

giotheninman

I have a stl list and i have a problem allocating memory for it. I am
using the malloc operator in order to get memory for it and I have
tried using placement new but it still isnt setting up the list
correctly.

The solution im looking for is something as follows

myObj->std::list<tObj> = (std::list<tObj>
*)malloc(sizeof(std::list<tObj>));
SetupListWithoutGettingNewMemory(myObj->std::list<tObj>);
myObj->myList->insert(something);
 
V

Victor Bazarov

I have a stl list and i have a problem allocating memory for it. I am
using the malloc operator in order to get memory for it and I have
tried using placement new but it still isnt setting up the list
correctly.

The solution im looking for is something as follows

myObj->std::list<tObj> = (std::list<tObj>
*)malloc(sizeof(std::list<tObj>));
SetupListWithoutGettingNewMemory(myObj->std::list<tObj>);
myObj->myList->insert(something);

What you're looking for is probably the "placement new" operator. You
will need to include <memory> header and use something like

void* buffer = malloc(sizeof(std::list<tObj>));
myObj->myList = new (buffer) std::list<tObj>;
myObj->myList->insert(something);

The funny thing, of course, is that while you will be allocating the
memory for the list itself, you're still allowing the list to allocate
memory for the objects it creates. In order to take control over that,
you need to learn to use "allocators". You can also overload the 'new'
and 'delete' for your class ('tObj') and those things will be called
when another object of 'tObj' type is about to be created...

V
 
B

Bernd Strieder

Hello,

you need to learn to use "allocators". You can also overload the
'new' and 'delete' for your class ('tObj') and those things will be
called when another object of 'tObj' type is about to be created...

But overloading new and delete for tObj won't help anything here. The
tObj instances are usually put into objects of a class used for the
nodes, which will be allocated by the allocator object given by default
or by the user to the list object at construction time. All you can do
is learning to use allocators.

There is no sensible reason to use malloc in this way. If you write why
you cannot live with the defaults, perhaps you can get better advice.

Bernd Strieder
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Correct javascript generates problems 1
how to use a pool 4
Problems with STL sorting using member functions 3
STL list or map? 33
Array using STL 7
STL list Problems 17
C++ STL List implementation 2
STL set Problem 5

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,286
Latest member
ChristieSo

Latest Threads

Top