#include <iostream>
#include <vector>
using namespace std;
// Shows Factor Design Pattern
class Stooge{
public:
static Stooge* makeStooge(int choice); // static class function
virtual void slapStick() = 0; // implemented by derived
virtual ~Stooge(){}
};
class Larry : public Stooge{
public:
void slapStick(){
cout << "Larry: poke eyes" << endl;
}
~Larry(){}
};
class Moe : public Stooge{
public:
void slapStick(){
cout << "Moe: slap head" << endl;
}
~Moe(){}
};
class Curly : public Stooge{
public:
void slapStick(){
cout << "Curly: suffer abuse" << endl;
}
~Curly(){}
};
Stooge* Stooge::makeStooge(int choice){
switch(choice){
case 1: return new Larry;
break;
case 2: return new Moe;
break;
case 3: return new Curly;
break;
default:{
cout << "Enter valid choice next time!!";
return NULL;
}
}
}
int main(){
vector<Stooge*> roles;
int choice;
while(true){
cout << "Larry(1) Moe(2) Curly(3) Exit(0)" << endl;
cin >> choice;
if(choice==0)
break;
Stooge *s = Stooge::makeStooge(choice);
if(s)
roles.push_back(s);
}
for(auto r : roles)
r->slapStick();
// this will fail
for(auto x : roles)
delete[] x;
// this works
#if 0
for(int i=0; i<roles.size(); i++)
delete roles[i];
#endif
return 0;
}当我运行上面的片段时,我会看到一个带有以下错误消息的崩溃:
a.out(48873,0x7fff75912000) malloc:*对象0x7fab72500058:指针未分配
在delete[]的调用堆栈中,我看到了一个有效的(malloc‘’ed)地址,用于'x‘,但我无法理解为什么实际空闲的情况与正则for循环(没有C11特性的情况下可以正常工作)存在问题。这意味着我不完全理解如何使用自动循环功能-谁能解释一下吗?
发布于 2015-11-09 20:37:00
x是roles中的单个元素。因为它是用new分配的,所以应该用delete (就像第二个块那样)释放它,而不是用delete[]。
https://stackoverflow.com/questions/33617724
复制相似问题