有人发布了关于这种模式的问题,但没有在我脑海中提出问题的解决方案,所以发布了我的查询......
在上面的示例中,如果所有实例都由 s_prototypes 变量初始化,并且下一次如果其中的任何对象将被克隆方法中的新对象替换,那么现有对象会发生什么?它会造成内存泄漏吗?
据我从上面的例子中了解到,两个陈述让我感到困惑
class Stooge {
public:
virtual Stooge* clone() = 0;
virtual void slap_stick() = 0;
};
class Factory {
public:
static Stooge* make_stooge( int choice );
private:
static Stooge* s_prototypes[4];
};
int main() {
vector roles;
int choice;
while (true) {
cout << "Larry(1) Moe(2) Curly(3) Go(0): ";
cin >> choice;
if (choice == 0)
break;
roles.push_back(
Factory::make_stooge( choice ) );
}
for (int i=0; i < roles.size(); ++i)
roles[i]->slap_stick();
for (int i=0; i < roles.size(); ++i)
delete roles[i];
}
class Larry : public Stooge {
public:
Stooge* clone() { return new Larry; }
void slap_stick() {
cout << "Larry: poke eyes\n"; }
};
class Moe : public Stooge {
public:
Stooge* clone() { return new Moe; }
void slap_stick() {
cout << "Moe: slap head\n"; }
};
class Curly : public Stooge {
public:
Stooge* clone() { return new Curly; }
void slap_stick() {
cout << "Curly: suffer abuse\n"; }
};
Stooge* Factory::s_prototypes[] = {
0, new Larry, new Moe, new Curly
};
Stooge* Factory::make_stooge( int choice ) {
return s_prototypes[choice]->clone();
}
Output
Larry(1) Moe(2) Curly(3) Go(0): 2
Larry(1) Moe(2) Curly(3) Go(0): 1
Larry(1) Moe(2) Curly(3) Go(0): 3
Larry(1) Moe(2) Curly(3) Go(0): 0
Moe: slap head
Larry: poke eyes
Curly: suffer abuse
但是当我们通过 make_stooge 方法调用 clone 方法时,它会返回新对象,如果返回新对象并将其替换为现有对象,则现有对象将在此处创建内存泄漏(因为 new 运算符完全创建单独的对象,而不是在此处返回现有对象) ……
所以这件事让我对这个例子感到困惑......