首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

DP_Factory, C++, Memory Leak?解决思路

2012-02-05 
DP_Factory, C++, Memory Leak?Hi guys,After I tried factory pattern, I have a question that who is r

DP_Factory, C++, Memory Leak?
Hi guys,

After I tried factory pattern, I have a question that who is responsible for delete memory?

Just for C++. Any idea? 


The following sample is from net.

C/C++ code
#include <iostream>#include <string>using namespace std;// Abstract base classclass Mobile {    public:       virtual string Camera() = 0;       virtual string KeyBoard() = 0;       void PrintSpecs() {          cout << Camera() << endl;          cout << KeyBoard() << endl;       }};// Concrete classesclass LowEndMobile : public Mobile {    public:       string Camera() {          return "2 MegaPixel";       }       string KeyBoard() {          return "ITU-T";       }};// Concrete classesclass HighEndMobile : public Mobile {    public:       string Camera() {          return "5 MegaPixel";       }       string KeyBoard() {          return "Qwerty";       }};// Abstract Factory returning a mobileclass MobileFactory {    public:       Mobile* GetMobile(string type);};Mobile* MobileFactory::GetMobile(string type) {    if ( type == "Low-End" ) return new LowEndMobile();    if ( type == "High-End" ) return new HighEndMobile();    return NULL;}void main(){   MobileFactory* myFactory = new MobileFactory();   Mobile* myMobile1 = myFactory->GetMobile("Low-End");   myMobile1->PrintSpecs();   Mobile* myMobile2 = myFactory->GetMobile("High-End");   myMobile2->PrintSpecs();}OUTPUT:2 MegaPixelITU-T5 MegaPixelQwerty



[解决办法]
keep in mind, it's a sample of design pattern, not memory management. it's unworthy for a sample to keep every aspect of a program fine.

热点排行