Last active
July 12, 2019 21:52
-
-
Save zhangxiaomu01/ace9aee1fb267810ac70bd7d0f975140 to your computer and use it in GitHub Desktop.
This file contains 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
void booFunc(){ | |
//Another way to create a shared pointer: | |
//Faster and safer/ Exception safe | |
shared_ptr<Dog> p = make_shared<Dog>("Ink"); | |
shared_ptr<Dog> p1 = make_shared<Dog>("Gunner"); | |
shared_ptr<Dog> p2 = make_shared<Dog>("Tank"); | |
// In the following situation, Gunner is deleted | |
p1 = p2; | |
//p1 = nullptr; | |
//p1.reset(); | |
//Sometimes we have to use constructor to create shared pointer | |
//instead of make_shared<class>(). We will take a look at below: | |
//using default deleter: operator delete | |
shared_ptr<Dog> p3 = make_shared<Dog>("Shooter"); | |
//Define our own custome deleter | |
shared_ptr<Dog> p4 = shared_ptr<Dog>(new Dog("Tank"), [](Dog* p){cout << "Custome deleting."; delete p;}); | |
//Dog[1] and Dog[2] have memory leak. | |
shared_ptr<Dog> p5(new Dog[3]); | |
//All 3 dogs will be deleted when p goes out of scope | |
shared_ptr<Dog> p6(new Dog[3], [](Dog* p){delete[] p;}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment