LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   stl containers (https://www.linuxquestions.org/questions/programming-9/stl-containers-53854/)

champ 04-07-2003 11:47 AM

stl containers
 
I just have a little question regarding how the stl containers handles memory.

I have allocated memory for a object and then the object is added to an stl list:

Code:

std::list<NewUser> userlist;
......
// adds item to vector
NewUser *user = new NewUser();
userlist.push_back(*user);
.......

// removes item from vector
userlist.pop_front();

I just wondered if the pop_front function frees the memory that I allocated earlier.
If not, how would i do that. The pop_front() function does'nt return the item popped off, does it? If it does I could just run delete on it, but I don't think you can do that?

BTW, the "user" pointer will only point to the current object created, so I will not have a pointer to the objects since this will be run in a function.

The best solution here maybe would not to use a pointer to the object at all, because I don't think I will need them.

But anyway, I would really like to know how it works.

GtkUser 04-07-2003 05:34 PM

//Allows you to use polymorphism if NewUser is a base class
std::list<NewUser*> userlist;
Yes, you have to free the object manually.

//If you need to use sort on std::list<T*>
bool compare_NewUser_ptrs( const NewUser* cp1, const NewUser * cp2 ) {
return compare( *cp1, *cp2);
}
...
sort(userlist.begin(), userlist.end(), compare_NewUser_ptrs);

I think that one way to be efficient with containers is to simply pass the container by reference as a function argument:
std::list<NewUser> userlist;
NewUser record;
//Fill Record here
userlist.push_back(record);
FunctionCall( userlist );

//Pass list by reference to a function
void FunctionCall( std::list<NewUser> & a , ...);

The containers use iterators to manage the objects they contain. I hear a good book on the subject is Generic Programming and the STL by Austern. The details are over my head but basically use the pointer syntax std::list<T*> and you have to call delete on the elements, but I can't say I've used it more than once in the past, and I'm not sure how all the std::list member functions would work with pointers, but it is legal.

champ 04-09-2003 05:27 AM

thanks for the tips GtkUser.

One of my problems was that the list contained references instead of pointers.

So now there is no problem iterate through the list and free the memory.


All times are GMT -5. The time now is 09:49 PM.