您的应用程序出现段错误,因为调用析构函数时对象不再存在。
该takeObjs
方法接收对对象的引用,然后将指向该对象的指针存储在向量中。该对象在其他地方定义。当该对象超出范围时,它会自动销毁。
当您到达析构函数时,该对象已被销毁。该应用程序出现段错误,因为您试图再次销毁它。
您应该阅读 C++ 中对象的范围(阅读此问题的答案),还应该阅读C++ 中的对象破坏。
编辑:添加简短示例来说明崩溃
#include <iostream>
#include <vector>
using namespace std;
class Object {
public:
int a;
int b;
Object(int a, int b)
{
this->a=a;
this->b=b;
}
};
class Test
{
std::vector<Object*> objects;
public:
Test(){}
void Add(Object &obj)
{
objects.push_back(&obj);
}
void Print()
{
for(unsigned int i=0;i<objects.size();i++)
{
cout<<objects[i]->a<<" "<<objects[i]->b<<endl;
}
}
~Test()
{
for (unsigned int i = 0; i < objects.size(); ++i){
delete objects[i];
}
objects.clear();
}
};
void AddNewObjects(Test &t)
{
Object x(1,2);
Object y(3,4);
t.Add(x);
t.Add(y);
// you can access your objects here
t.Print();
}
int _tmain(int argc, _TCHAR* argv[])
{
Test t;
AddNewObjects(t);
// but if you try to access the objects here, you get a crash
// because the objects were destroyed when exiting "AddNewObjects"
t.Print();
return 0;
// your destructor tries to access the objects here (in order to destroy them)
// and that's why it crashes
}
这是您可以用来解决问题的一种解决方案:
#include <iostream>
#include <vector>
using namespace std;
class Object {
public:
int a;
int b;
Object(int a, int b)
{
this->a=a;
this->b=b;
}
};
class Test
{
std::vector<Object*> objects;
public:
Test(){}
void Add(Object *pObj)
{
objects.push_back(pObj);
}
void Print()
{
for(unsigned int i=0;i<objects.size();i++)
{
cout<<objects[i]->a<<" "<<objects[i]->b<<endl;
}
}
~Test()
{
for (unsigned int i = 0; i < objects.size(); ++i){
delete objects[i];
}
objects.clear();
}
};
void AddNewObjects(Test &t)
{
Object* x = new Object(1,2);
Object* y = new Object(3,4);
t.Add(x);
t.Add(y);
// you can access your objects here
t.Print();
}
int _tmain(int argc, _TCHAR* argv[])
{
Test t;
AddNewObjects(t);
// you can also access the objects here
// because they are not destroyed anymore when exiting "AddNewObjects"
t.Print();
return 0;
}