Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created July 12, 2019 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/8900704cfb47c5f88bc4fa70c5ce5f7b to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/8900704cfb47c5f88bc4fa70c5ce5f7b to your computer and use it in GitHub Desktop.
void foo_01Func(){
Dog* d = new Dog("Tank"); //Should not use
shared_ptr<Dog> p(d); // p.get_count() == 1
//Here when p goes out of scope, d will be destroyed.
//Then p2 goes out of scope, p2 will be destroyed again...
shared_ptr<Dog> p2(d); // p2.get_count() == 1, the counter won't increase
/* Lesson: An object should be assigned to a shrared_pointer
immediately when it is created. The above case does not follow
this rule. We first create the raw pointer d and then initialize
p and p2 with d. We should do somthing like:
shared_ptr<Dog> p(new Dog("Tank")), then shared_ptr<Dog> p2 = p.*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment