Created
July 12, 2019 22:42
-
-
Save zhangxiaomu01/e18acd945997ebd4249507211adf0bbd 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
#include<iostream> | |
#include<string> | |
#include<memory> | |
using namespace std; | |
class Dog { | |
weak_ptr<Dog> m_pFriend; | |
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; } | |
void showFriend() { | |
//Compile error. m_pFriend cannot direct access the object like the normal pointer. | |
//cout << "My Friend is: " << m_pFriend->m_name << endl; | |
// The following code fix the problem. lock() function will create | |
//a shared_ptr of weak_ptr. It will check whether the weak pointer | |
//is still pointing to a valid object, and make sure that when the | |
// weak pointer is accessing the object, the object has not been | |
//deleted! | |
//If the weak pointer is empty, the lock() will throw an exception. | |
if (!m_pFriend.expired()) | |
cout << "My Friend is: " << m_pFriend.lock()->m_name << endl; | |
cout << "He is owned by " << m_pFriend.use_count() << " pointers" << endl; | |
} | |
}; | |
int main() { | |
shared_ptr<Dog> pD(new Dog("Gunner")); | |
shared_ptr<Dog> pD1(new Dog("Smile")); | |
pD->makeFriend(pD1); | |
pD1->makeFriend(pD); | |
pD->showFriend(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment