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
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