【发布时间】:2012-07-23 23:06:28
【问题描述】:
我在函数之间传输向量中包含的某些数据时遇到问题。情况如下:
void generateObjects(std::vector<MyClass> &objects)
{
objects.clear();
//Fill objects vector
std::vector<MyClass> p;
//This 4-line pattern is repeated a number of times to generate all objects and store them in variable 'objects'
p.clear();
generateSomeOfTheObjects(p); //p is again passed by ref. in/out parameter
for(uint j = 0; j < p.size(); p++){
objects.push_back(p[j]);
}
//Print some members of the objects - works fine
for(uint i = 0; i < objects.size(); i++){
printf("%f ",objects[i].mymember->myElm);
}
}
int main()
{
std::vector<MyClass> objects;
generateObjects(objects);
//Print size of vector - size is correct it is the same as it is in generateObjects func
printf("%lu\n",objects.size());
//Again print members of the objects - some members are retained after the function call, some are lost.
//The one below doesn't work, mymember is a pointer to another object and its member myElm seems not initialized.
for(uint i = 0; i < objects.size(); i++){
printf("%f ",objects[i].mymember->myElm);
}
//Here I need to pass the objects to another read-only function
...
}
我在互联网上搜索过类似的案例,实际上发现了很多,但我无法对我的代码应用相同的修复。我正在尝试访问 MyClass 实例的成员 (objects[i].mymember->myElm) 指向的对象的成员,我在这里可能遗漏了什么?
【问题讨论】:
-
您需要显示填充向量的代码。你这里的东西看起来不错。
-
MyClass中有哪些数据成员? -
你为什么要清除
objects,创建一个新的vector p,填充然后复制到objects? -
@guenis,供您参考,Rule of Three。这可能是问题所在,也可能不是,但如果是这样,那将有所帮助。如果您的类在构造函数中为
mymember分配内存,在析构函数中释放它,并且没有(正确的)复制(/移动)构造函数/赋值运算符,则很可能是问题所在。 -
实现三规则正确性的简单方法是使用智能指针来避免它。 Proof your code works if
MyClassis properly implemented
标签: c++ parameter-passing stdvector