所以我试图弄清楚如何创建一个可以动态分配和销毁自身的C ++类。我想到了以下
class tClass {
public:
tClass() {
c = 0;
extra = new int[1024 * 1024]; // To see memory usage
while (true) {
if (c != 1) {
std::cout << "Name the class: ";
std::cin >> str;
}
std::cout << "1 = create a new instance, 2 = delete this instance\n";
std::cin >> c;
if (c == 1) {
tclass = new tClass();
}
else {
break;
}
}
delete[] extra;
this->~tClass();
}
~tClass() {
std::cout << "tClass " << str << " destroyed\n" << std::endl;
}
private:
std::string str;
tClass* tclass;
int c;
int* extra;
};
int main () {
tClass *tclass = new tClass();
delete tclass;
return 0;
}
它可以工作,但是我确定它不能以健康的方式工作。它真的释放了它使用的所有内存吗?最终将“ delete [] extra”放入析构函数中会给我带来内存访问冲突错误。
答案 0 :(得分:0)
我自己弄清楚了。谢谢mr5给我提示。
class Slave {
public:
Slave(const std::string& str): _str(str) {
std::cout << "Slave " << _str << " was created\n";
}
~Slave() {
std::cout << "Slave " << _str << " was destroyed\n";
}
private:
std::string _str;
};
class Master {
public:
Master() {
while (true) {
std::cout << "1 = create new, 2 = delete latest\n";
std::cin >> c;
if (c == 1)
Create();
else
if (!Destroy())
break;
}
}
~Master() {}
void Create() {
std::cout << "Name the new class: ";
std::cin >> str;
slaves.push_back(new Slave(str));
}
bool Destroy() {
if (slaves.size() > 0) {
delete slaves[slaves.size() - 1];
slaves.pop_back();
return true;
} else
return false;
}
private:
std::string str;
std::vector<Slave*> slaves;
int c;
};
int main()
{
Master* master = new Master();
delete master;
return 0;
}