Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created July 12, 2019 22:28
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/69ed382c8c628daff2dc8982a4500f23 to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/69ed382c8c628daff2dc8982a4500f23 to your computer and use it in GitHub Desktop.
class Dog {
shared_ptr<Dog> m_pFriend;//cyclic reference
//weak_ptr<Dog> m_pFriend; //Solution to fix the problem
public:
string m_name;
Dog(string name) : m_name(name){cout << "Dog: " << m_name << " is defined!" << endl;}
void bark() {cout << "Dog " << m_name << " rules!" << endl;}
~Dog() {cout << "Dog is destroyed: " << m_name << endl;};
void makeFriend(shared_ptr<Dog> f){m_pFriend = f;}
};
int main(){
shared_ptr<Dog> pD(new Dog("Gunner"));
shared_ptr<Dog> pD1(new Dog("Smile"));
pD->makeFriend(pD1);
pD1->makeFriend(pD);
//In this code, Dog destructor will not be called, when pD goes out of scope,
//pD1 still has a pointer points to pD; when pD1 goes out of scope, pD still
//has a pointer points to pD1
//Will cause memory leak: cyclic reference!
//using weak pointer to declare m_pFriend.
//Weak pointer has no ownership of the pointed object.
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment