开发者

Vector of object pointers containing vectors end up pointing to same object

I am storing multiple objects in a vector of pointers to these objects, like so, in C++:

vector<Host *> somevector;

I then initialize each item like this:

somevector.push_back(new Host(x));

The object takes an initializing argument. As I read through data (strings) and end up with a list of object pointers, I add them to an internal vector inside the object itself:

somevector.at(i)->add(string data);

However, it appears that all the data have been added to the same object, and even though the objects have different names, their internal vector that stores this data are identical.

I searched various keywords to solve this and I think it is an issue with a copy constructor (I currently am using default). How do I account for the vector inside the object that I am copying? Do I have to make the vector in the object a field so that a new one is created in the copy constructor?

EDIT:

I've replicated the code for the object class:

vector<stri开发者_开发技巧ng> v;

Host::Host(string _x): x(_x)
{
}

Host::~Host()
{
}

string Host::name()
{
  return x;
}

string Host::link(int r)
{
  int i = r % v.size();
  return v.at(i);
}

void Host::add(string data)
{
  v.push_back(data);
}

So I am using this vector inside the host object to store a bunch of strings. Then, when I call link from my main program, I pass it a random number, and I want to get a random string from the list inside the object. However, my link() calls are coming back with strings that should not have been stored into the object.


From what I can see from the example code you have posted 'v' isn't a member object of Host. So calls to Host::add are simply pushing back to a globally available vector. Is this perhaps where your problem is?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜