Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
class Dog {
shared_ptr<Dog> m_pFriend;//cyclic reference
//weak_ptr<Dog> m_pFriend; //Solution to fix the problem
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"));
//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