In my C ++ code, I have an Object class equipped with an id field of type int. Now I want to create a pointer vector of type Object *. I tried first
vector<Object*> v; for(int id=0; id<n; id++) { Object ob = Object(id); v.push_back(&ob); }
but this did not succeed, because here the same address is simply repeated n times. If I used the new operator, I would get what I want, but I would like to avoid the dynamic allocation of memory. Then I thought that I needed to somehow declare n different pointers before the for loop. The direct way to do this is to declare an array, so I did this:
vector<Object*> v; Object ar[n]; for(int i=0; i<n; i++) { ar[i] = Object(i); } for(int i=0; i<n; i++) { v.push_back(ar+i); }
Is it possible to get a memory leak if I do this? Also, in my opinion, considering declaring an array is a bit awkward. Are there other ways to create a pointer vector, but avoid manual memory management?
EDIT: Why do I need pointers instead of simple objects?
Well, I changed the initial situation a bit, because I thought that I could present the question in the simplest possible form. In any case, I still think that the question can be answered without knowing why I want a pointer vector.
Actually, I have
Class A { protected: vector<Superobject*> vec; ... }; Class B: public A {...}; Class Superobject { protected: int id; ... } Class Object: public Superobject {...}
In the derived class B I want to populate the vec member field with objects of type Object . If the superclass didn't use pointers, I would have problems with trimming objects. Therefore, in the class B constructor, I want to initialize vec as a vector of pointers of type Object* .
EDIT2
Yes, it seems to me that dynamic allocation is a reasonable option, and the idea of ββusing an array is a bad idea. When the array goes out of scope, everything will go wrong, because the pointers in the vector point to memory cells that do not necessarily contain objects anymore.
In the constructor for class B, I had
B(int n) { vector<Object*> vec; Object ar[n]; for(int id=0; id<n; id++) { ar[id] = Object(id); } for(int id=0; id<n; id++) { v.push_back(ar+id); } }
This caused a very strange behavior in class B objects.