【发布时间】:2015-09-16 13:55:33
【问题描述】:
感谢 Windows 资源监视器,我正在测试此代码以了解如何管理程序内存。
class A {
public:
string name_;
vector<double> H;
vector<float> G;
vector<string> I;
int abc;
};
list<A *> test (90000);
void allocate_class() {
for (list<A *>::iterator it= test.begin(); it != test.end();it++) {
A *ptr=*it;
ptr = new A;
}
}
void init_fct() {
for (list<A *>::iterator it= test.begin(); it != test.end();it++) {
A *ptr=*it;
/*
all above doesnt work program crash
(*ptr).name_ = "hello test";
ptr->name_ = "hello test";
ptr->abc = 57;
*/
}
}
void erase_class() {
list<A *>::iterator it= test.begin();
while( it != test.end() )
it = test.erase(it);
}
void delete_ptr() {
for (list<A *>::iterator it= test.begin(); it != test.end();it++) {
A *ptr=*it;
delete ptr;
}
}
int main()
{
int t;
cout << "before allocation" << endl;
cin >> t;
allocate_class();
cout << "after allocation" << endl;
cin >> t;
init_fct();
cout << "after init" << endl;
cin >> t;
erase_class();
cout << "after erase" << endl;
cout << test.size();
cin >> t;
delete_ptr();
cout << "after delete" << endl;
cout << test.size();
cin >> t;
问题:
在这种情况下真的需要操作符删除部分吗? (不确定它是否真的可用空间)
init_fct()中我做错了什么/遗漏了什么?
注意:(属性是故意公开的,cin是暂停程序并检查内存状态)
【问题讨论】:
标签: c++ pointers memory-management linked-list