I need to create object pointers in a loop, but I am struggling with creating unique pointers. Here’s my code:
class DatClass{
public:
int m;
DatClass(int i):m(i){}
};
class OtherClass{
public:
DatClass* dc;
};
void Test(std::vector<OtherClass> v){
std::vector<OtherClass>::iterator it;
int i = 1;
for(it = v.begin(); it != v.end(); it++){
DatClass dc = DatClass(i);
std::cout << &dc << std::endl;
it->dc = &dc;
i++;
}
}
int main(){
std::vector<OtherClass> v;
v.push_back(OtherClass());
v.push_back(OtherClass());
v.push_back(OtherClass());
Test(v);
}
This does not give me unique pointers. The output reads:
0xbf94d72c
0xbf94d72c
0xbf94d72c
Do I need to use new in order to get unique pointers? If so, where would I put the corresponding delete?
Thanks!
Yes, you should use
newto get unique addresses.The
deleteshould be when the loop is done – otherwise (delete is inside the same loop) – the OS could give you the same address again.(Or to be exact – when you are done with the object allocated in this address)
What’s going on in your code is that you use an automatically allocated memory. This memory is usually allocated on the stack – and in each iteration – the same memory is reused for the variable – thus it gives you the same address.