类对象指针的C ++向量

问题描述:

我想做的基本上是创建两个对象向量,其中一些对象被输入到两个列表中,而另一些则被输入到一个列表中.我发现的第一个问题是,当我使用push_back()将一个对象添加到两个列表中时,该对象已被复制,因此当我从一个列表中更改该对象时,该对象在另一个列表中却没有更改.为了解决这个问题,我尝试创建一个指向对象的指针列表作为列表之一.但是,当我稍后在数据*问指针时,似乎已损坏该数据成员值,这都是错误的.这是我的代码的一些摘要:

What I am trying to do is essentially create two vectors of objects, where some objects are entered into both lists and some are just entered into one. The first problem I found was that when I used push_back() to add an object into both lists the object was copied so that when I changed it from one list the object did not change in the other. To get around this I tried to create a list of pointers to objects as one of the lists. However when I accessed the pointer later on the data seemed to be corrupted, the data member values were all wrong. Here are some snippets of my code:

向量的定义:

vector<AbsorbMesh> meshList;
vector<AbsorbMesh*> absorbList;

... 向两个对象添加对象:

... Adding an object to both:

AbsorbMesh nurbsMesh = nurbs.CreateMesh(uStride, vStride);

// Add to the absorption list
absorbList.push_back(&nurbsMesh);
// Store the mesh in the scene list
meshList.push_back(nurbsMesh);

访问对象:

if (absorbList.size() > 0)
{
float receivedPower = absorbList[0]->receivedPower;
}

我在做什么错了?

缺少一些详细信息,但这是一个猜测.

There's some details missing, but at a guess.

nurbsMeshpush_backabsorbList[0]->receivedPower之间超出范围.

nurbsMesh goes out of scope between the push_back and the absorbList[0]->receivedPower.

所以现在您的指针向量包含一个指向不再存在的对象的指针.

So now your vector of pointers contains a pointer to an object that doesn't exist anymore.

尝试将复制构造函数添加到AbsorbMesh类中,然后将其添加到向量中.

Try adding a copy constructor to your AbsorbMesh class and adding to your vector like this.

absorbList.push_back(new AbsorbMesh(nurbsMesh));
meshList.push_back(nurbsMesh);

不要忘记删除absorbList中的对象,就像这样

don't forget to delete the objects in absorbList, like this

for(vector<AbsorbMesh*>::iterator it = absorbList.begin(); it != absorbList.end(); it++) {
    delete it;
  }

或将共享指针存储在向量中,而不是裸指针.如果您感兴趣的话,Boost具有良好的共享指针实现.请参见此处

Or store a shared pointer in your vector instead of a bare pointer. Boost has a good shared pointer implementation if you're interested. See the docs here

如果要更新一个向量中的项目,请修改另一个向量中的对象,则需要将指针存储在两个向量中.

If you want to have updates to items in one vector modify objects in the other vector, then you'll need to store pointers in both vectors.

使用您的原始要求(更新一个向量中的项目会影响另一向量中的项目,这就是我如何使用boost共享指针来完成此操作.(警告,未经测试的代码)

Using your original requirements (updating an item in one vector affects items in the other vector, here's how I'd do it with a boost shared pointer. (WARNING, untested code)

vector<boost::shared_ptr<AbsorbMesh> > meshList;
vector<boost::shared_ptr<AbsorbMesh> > absorbList;

boost::shared_ptr<AbsorbMesh> nurb = new AbsorbMesh(nurbs.CreateMesh(uStride, vStride));

meshList.push_back(nurb);
absorbList.push_back(nurb);

...
...

if (absorbList.size() > 0)
{
    float receivedPower = absorbList[0].get()->receivedPower;
}