|
|
| stl list and pointers |
|
Frank Drebin
Member #2,987
December 2002
|
i have a stl list of myclass and a pointer to a myclass-objects. now i do listofmyclass.push_back() to create one object of myclass. how can i now assign the pointer to the myclass-object to the new object that was just created? |
|
23yrold3yrold
Member #1,134
March 2001
|
mypointer = &mylist.back();
-- |
|
gillius
Member #119
April 2000
|
listofmyclass.push_back() is invalid C++ code. You need to push back some object. If you do that you have a pointer to it. You can do this: listofmyclass.push_back( MyClass() ); MyClass* = &(*listofmyclass.rbegin()); I believe. Gillius |
|
Frank Drebin
Member #2,987
December 2002
|
Quote: mypointer = &mylist.back();
sounds good i'll test it. |
|
Tobias Dammers
Member #2,604
August 2002
|
But if you do this: list<MyClass> listofmyclass; MyClass* mc = new MyClass(); listofmyclass.push_back(*mc); mc = &listofmyclass.back();
you'll leak memory. The memory allocated in line 2 is copied to a new list entry in line 3. Then the pointer is set to the copy in line 4, leaving the original data allocated, but unreferenced. list<MyClass> listofmyclass; MyClass* mc = new MyClass(); listofmyclass.push_back(*mc); delete mc; mc = &listofmyclass.back(); or: list<MyClass*> listofmyclass; MyClass* mc = new MyClass(); listofmyclass.push_back(mc); // ...and somewhere else to clean up: MyClass* mc = &listofmyclass.pop_back(); delete mc; // or something similar. ...in which case you will have to delete all list entries yourself when you no longer need them. The list now only holds pointers to objects. --- |
|
Frank Drebin
Member #2,987
December 2002
|
i'm not talking about a list of pointers but a list of objects. so no new or delete. |
|
axilmar
Member #1,204
April 2001
|
Do the easy thing of first storing the created value in a local pointer, then push back the local pointer's value: MyClass *obj = new MyClass(); objList.push_back(obj);
|
|
X-G
Member #856
December 2000
|
Quote: i was wondering if this would work: pointer=& (*iteratorformylist) It should. The reason mypointer=&mylist.begin(); doesn't work is because begin() is an iterator, not an element. mypointer=&mylist.first() should work. -- |
|
23yrold3yrold
Member #1,134
March 2001
|
Quote: It should. The reason mypointer=&mylist.begin(); doesn't work is because begin() is an iterator, not an element. mypointer=&mylist.first() should work. The function is front(), not first(). -- |
|
X-G
Member #856
December 2000
|
Yes, well, uh ... LOOK BEHIND YOU! A THREE-HEADED MONKEY! -- |
|
Frank Drebin
Member #2,987
December 2002
|
where? someone said that list.push_back() is invalid. |
|
X-G
Member #856
December 2000
|
Yes - you can't push nothing onto a list. You need to make an object and push it. -- |
|
|