How to get a pointer out of scope
This is not exactly my code but it looks a lot like it
I have 2 tables of type CTable. They work in the same way as normal arrays but can be allocated dynamically and resized. So lets just pretend that they are arrays right now
One table has object references
MyObj obj1;
MyObj obj2;
MyObj table1[10];
table1[0] = obj1;
table1[1] = obj2;
Now because I want to order them differently someti开发者_如何学编程mes, I've put pointers to these objects in another table
MyObj *table2[10];
table2[0] = &table1[0];
table2[1] = &table1[1];
Is there a way to get a reference to obj1 and obj2 through table2 so those object will get out of scope at the end of some kind of delete function
something like
void free() {
MyObj &obj = *table2[0];
}
and then bang, at the end of free, obj is delete automagically. Also, some kind of way to delete these objects through table2 would be acceptable.
If you want to control the objects' lifetime, you'll need to allocate them dynamically. In that case, your code would look something like this:
vect2.push_back(new MyObj);
vect2.push_back(new MyObj);
void func() {
MyObj &obj = *vect2[0];
// ...
vect2.erase(vect2.begin());
delete &obj;
}
In your case it good to be a one vector with just only pointers.
If it doesn't fits try this:
for(UINT i=0;i<vect1.size();++i)
{
MyObj * p = &vect1[i];
vect2.push_back(p);
}
// This is example of adding
P.S.
vector<MyObj*> vect2;
vect2.push_back(&obj1);
vect2.push_back(&obj2);
this code is wrong
精彩评论