From fc2a8f5cb99a674918619bc3585815796e175411 Mon Sep 17 00:00:00 2001 From: henrytien Date: Wed, 23 Nov 2022 03:04:36 +0000 Subject: [PATCH] fix:segment core if not initialize the pointer --- CreationalPatterns/prototype/Prototype.cxx | 32 +++++++++++++--------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/CreationalPatterns/prototype/Prototype.cxx b/CreationalPatterns/prototype/Prototype.cxx index 57d787c..595737e 100644 --- a/CreationalPatterns/prototype/Prototype.cxx +++ b/CreationalPatterns/prototype/Prototype.cxx @@ -9,7 +9,7 @@ #include class Prototype { -public: + public: Prototype() { std::cout << "Prototpye" << std::endl; } virtual ~Prototype() {} @@ -18,33 +18,40 @@ class Prototype { }; class ConcreatePrototype1 : public Prototype { -public: + public: ConcreatePrototype1() { std::cout << "ConcreatePrototype1" << std::endl; } ~ConcreatePrototype1() {} Prototype* clone() { return new ConcreatePrototype1; } - void checkPrototype() { std::cout << "Prototype1 has been created" << std::endl; } + void checkPrototype() { + std::cout << "Prototype1 has been created" << std::endl; + } }; class ConcreatePrototype2 : public Prototype { -public: + public: ConcreatePrototype2() { std::cout << "ConcreatePrototype2" << std::endl; } ~ConcreatePrototype2() {} Prototype* clone() { return new ConcreatePrototype2; } - void checkPrototype() { std::cout << "Prototype2 has been created" << std::endl; } + void checkPrototype() { + std::cout << "Prototype2 has been created" << std::endl; + } }; class Client { -public: - Client() { std::cout << "Client" << std::endl; } + public: + Client() { + prototype = NULL; + std::cout << "Client" << std::endl; + } ~Client() { if (prototype) { delete prototype; } } - void setPrototype(Prototype *p) { + void setPrototype(Prototype* p) { if (prototype) { delete prototype; } @@ -57,18 +64,17 @@ class Client { return prototype->clone(); } -private: - Prototype *prototype; + private: + Prototype* prototype; }; int main(int argc, char* argv[]) { Client client; client.setPrototype(new ConcreatePrototype1); - Prototype *p1 = client.clone(); + Prototype* p1 = client.clone(); p1->checkPrototype(); client.setPrototype(new ConcreatePrototype2); - Prototype *p2 = client.clone(); + Prototype* p2 = client.clone(); p2->checkPrototype(); - } \ No newline at end of file