Last active
January 31, 2018 14:19
-
-
Save ChunMinChang/3a31e610a032d00dd71a3b8c00be642b to your computer and use it in GitHub Desktop.
memory leak samples #cppTest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> // std::cout, std::endl; | |
#include <memory> // std::shared_ptr | |
#include <string> // std::string | |
#include <vector> // std::vector | |
class A | |
{ | |
public: | |
A() | |
{ | |
std::cout << "A is created" << std::endl; | |
} | |
~A() | |
{ | |
std::cout << "A is destroyed" << std::endl; | |
} | |
}; | |
class B | |
{ | |
public: | |
B(std::string s) | |
: id(s) | |
{ | |
std::cout << "B: " << id << " is created" << std::endl; | |
} | |
B(const B &obj) | |
: id(obj.id + "(copied)") | |
{ | |
std::cout << "B: is copied from " << obj.id << std::endl; | |
} | |
~B() | |
{ | |
std::cout << "B: " << id << " is destroyed" << std::endl; | |
} | |
private: | |
std::string id; | |
}; | |
A a[2]; | |
/*static*/ std::vector<B> b; | |
/*static*/ std::vector<B*> ptr; // Memory Leak! | |
/*static*/ std::vector<std::shared_ptr<B>> shrPtr; | |
int main() | |
{ | |
std::vector<B*> ptr; | |
// Create a B(1) and it's copied into b. | |
// The created B(1) will be destoryed after calling | |
// because its lifetime is within b.push_back(). | |
b.push_back(B("1")); | |
// Create a B(2) and put its address into ptr. | |
// Cause memory leak because there is no memory recall mechanism | |
// after ptr is destroyed when the program is finished. | |
ptr.push_back(new B("2")); | |
// To avoid the above case, we can use shared_ptr to manage allocated memory. | |
// The reference count to B(3) will be added to 1 from 0 | |
// when the share pointer to B(3) is created. | |
// Upon shrPtr is destroyed, the share pointer to B(3) | |
// in the vector will also be destroyed, so the reference count to B(3) | |
// will be subtracted to 0 from 1. When the reference count equals to 0, | |
// shared_ptr will deallocate the pointed address automatically. | |
shrPtr.push_back(std::shared_ptr<B>(new B("3"))); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment