Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix:segment core if not initialize the pointer #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions CreationalPatterns/prototype/Prototype.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
#include <string>

class Prototype {
public:
public:
Prototype() { std::cout << "Prototpye" << std::endl; }
virtual ~Prototype() {}

Expand All @@ -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;
}
Expand All @@ -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();

}