2

我得到了这个类来获取所有派生对象的列表

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;
 }

但对象仍被实例化

我没主意了^^

亲切地..

4

3 回答 3

3

注册::instances.clear();

这会清除指针列表,但不会对对象做任何事情。您需要在清除列表之前自己删除它们,例如这样

for (list<Register *>::iterator it = Register::instances.begin();
     it != Register::instances.end();
     ++it) {
    delete *it;
}
Register::instances.clear();
于 2012-08-15T14:30:00.493 回答
2

作为手动清除列表的替代方法,C++11 引入了与 STL 容器兼容的 std::unique_ptr<> 智能指针。

static std::list<std::unique_ptr<Register>> instances;

基本上会负责删除对象。

于 2012-08-15T14:37:46.007 回答
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();
于 2012-08-15T15:34:05.167 回答