push(ing)_back objects pointers within a loop
Posted
by
Jose Manuel Albornoz
on Stack Overflow
See other posts from Stack Overflow
or by Jose Manuel Albornoz
Published on 2012-07-10T15:10:52Z
Indexed on
2012/07/10
15:15 UTC
Read the original article
Hit count: 204
Consider the following: I have a class CDevices containing, amongst others, a string member
class CDevice
{
public:
CDevice(void);
~CDevice(void);
// device name
std::string Device_Name;
etc...
}
and somewhere else in my code I define another class that contains a vector of pointers to CDevices
class CDevice;
class CServers
{
public:
CServers(void);
~CServers(void);
// Devices vector
vector<CDevice*> Devices;
etc...
}
The problem appears in the following lines in my main.c
pDevice = new CDevice;
pDevice->Device_Name = "de";
Devices.push_back(pDevice);
pDevice->Device_Name = " revolotiunibus";
Devices.push_back(pDevice);
pDevice->Device_Name = " orbium";
Devices.push_back(pDevice);
pDevice->Device_Name = " coelestium";
Devices.push_back(pDevice);
for(int i = 0; i < (int)Devices.size(); ++i)
cout << "\nLoad name = " << Devices.at(i)->Device_Name << endl;
The output I get is " coelestium" repeated four times: each time I push_back a new element into the vector all of the already existing elements take the value of the one which has just been added. I have also tried using iterators to recover each element in the vector with the same results. Could someone please tell me what's wrong here?
Thankx
© Stack Overflow or respective owner