デストラクタが呼び出されたときにオブジェクトが存在しなくなったため、アプリのセグメンテーション違反。
このtakeObjs
メソッドは、オブジェクトへの参照を受け取り、そのオブジェクトへのポインターをベクター内に格納します。そのオブジェクトは別の場所で定義されています。そのオブジェクトがスコープ外になると、自動的に破棄されます。
デストラクタに到達するまでに、オブジェクトは破棄されます。アプリを再度破棄しようとしているため、アプリのセグメンテーション違反が発生します。
C++ でのオブジェクトのスコープについて読む必要があり (この質問への回答を読んでください) 、C++ でのオブジェクトの破壊についても読む必要があります。
EDIT:クラッシュを説明するために短い例を追加
#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
}
問題を解決するために使用できる 1 つの解決策を次に示します。
#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;
}