我在函数之间传输 vector 中包含的某些数据时遇到麻烦。情况如下:
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
的实现。我想说这个类包含一些用局部变量的地址初始化的指针,因此当您从某些函数返回时,该指针指向被破坏的对象。
那将是不确定的行为,但可能是偶然的。从第一个函数返回时,堆栈存储器最终将被覆盖,并且数据将丢失。
更新:由于@chris在下面的注释中提供的见解,最可能的原因是您的MyClass
没有副本构造函数,但是它确实具有指针成员。
像这样:
class MyClass
{
public:
Member *mymember;
MyClass()
{
mymember = new Member;
}
~MyClass()
{
delete mymember;
}
};
现在,如果使用编译器生成的默认副本构造函数(或副本运算符),会发生什么?
void foo()
{
MyClass a;
{
MyClass b(a);
}
//a.mymember is no longer valid
}
a
和b
都共享相同的指针mymember
,因此,当其中之一被销毁时,mymember
会被删除,而另一个则会悬挂一个指针。这就是为什么我们将规则设置为3 的原因。它指出:
现在,您必须决定是要共享
mymember
的所有权还是要复制它。第一个最好用智能指针(shared_ptr
)完成,第二个最好用深度复制。例如,深层复制:
class MyClass
{
public:
Member *mymember;
MyClass()
{
mymember = new Member;
}
MyClass(const MyClass &c)
{
mymember = new Member(c.mymember);
}
MyClass &operator=(const MyClass &c)
{
if (this != &c) //be aware of self-copy
{
delete mymember;
mymember = new Member(c.mymember);
}
return *this;
}
~MyClass()
{
delete mymember;
}
};
并使用共享指针:
class MyClass
{
public:
std::shared_ptr<Member> mymember; //or boost::shared_ptr if old compiler
MyClass()
:mymember(new Member)
{
}
//no custom-made destructor -> no rule of 3
};