我得到这个类来获取所有派生对象的列表
Register.h
-----------------
class Register {
...
public:
// static object list
static list<Register*> instances;
// default constructor for register object
Register::Register();
// virtual destructor to clean up with subobject destructor first
virtual Register::~Register();
// default methods for this class
static void Register::stop();
Register.cpp
-----------------
#include "Register.h"
// list with all object instances made by this programm
list<Register*> Register::instances;
// default destructor
Register::~Register() {
list<Register*>::iterator p = find(instances.begin(), instances.end(), this);
if (p != instances.end()) {
instances.erase(p);
}
}
// erase all instances clean up the dish
void Register::stop() {
// last log message
Log::write("register cleanup");
// stops the logging object
Log::stop();
// clean up instances
list<Register*>::iterator iter = instances.begin();
list<Register*>::iterator end = instances.end();
while (iter != end) {
cout<< endl << (*iter) -> typeName << endl;
//delete *iter;
}
Register::instances.clear();
}
和派生类
File.h
-----------------
class File : public Register {
...
// default destructor
virtual File::~File(void);
...
}
File.cpp
-----------------
// default destructor
File::~File(void) {
cout << "file destr";
this -> deleteFile();
}
Log.h
-----------------
// this class implements a log handler
// (derived from register)
class Log : public File {
public:
// singelton logging object
static Log* log;
// default destructor
Log::~Log(void);
Log.cpp
-----------------
using namespace std;
// declare pointer for easy logging
Log* Log::log = NULL;
// default destructor
Log::~Log(void) {
cout << "log destr";
}
现在我想删除整个结构,只需删除列表及其中的对象..
我试过
Main.cpp
-----------------
int main (int argc, char *argv[], char *envp[]) {
Register::stop();
return 1;
}
但对象仍然是实例
我没有想法^^
麻烦..
答案 0 :(得分:3)
注册:: instances.clear();
这会清除指针列表,但不会对对象执行任何操作。在清除列表之前,您需要自己删除它们,例如像这样
for (list<Register *>::iterator it = Register::instances.begin();
it != Register::instances.end();
++it) {
delete *it;
}
Register::instances.clear();
答案 1 :(得分:2)
作为手动清除列表的替代方法,C ++ 11引入了std :: unique_ptr&lt;&gt; smartpointer与STL容器兼容。
static std::list<std::unique_ptr<Register>> instances;
基本上会处理删除对象。
答案 2 :(得分:0)
好的..我解决了..
// clean up instances
list<Register*>::iterator iter = instances.begin();
list<Register*>::iterator end = instances.end();
while (iter != end) {
iter = instances.erase(iter);
}
Register::instances.clear();