C++ examples for Data Type:weak_ptr
Example Using weak_ptr
#include <string> #include <memory> using namespace std; class Book; // forward declaration of class Book class Author {//from w w w . ja v a 2s .c o m public: Author(const string &authorName); // constructor ~Author(); // destructor void printBookTitle(); // print the title of the Book string name; // name of the Author weak_ptr< Book > weakBookPtr; // Book the Author wrote shared_ptr< Book > sharedBookPtr; // Book the Author wrote }; class Book { public: Book(const string &bookTitle); // constructor ~Book(); // destructor void printAuthorName(); // print the name of the Author string title; // title of the Book weak_ptr< Author > weakAuthorPtr; // Author of the Book shared_ptr< Author > sharedAuthorPtr; // Author of the Book }; #include <iostream> using namespace std; Author::Author(const string &authorName) : name(authorName) { } Author::~Author() { cout << "Destroying Author: " << name << endl; } // end of destructor void Author::printBookTitle() { if (shared_ptr< Book > bookPtr = weakBookPtr.lock()) { cout << "Reference count for Book " << bookPtr->title << " is " << bookPtr.use_count() << "." << endl; cout << "Author " << name << " wrote the book " << bookPtr->title << "\n" << endl; } else // weakBookPtr points to NULL cout << "This Author has no Book." << endl; } Book::Book(const string &bookTitle) : title(bookTitle) { } Book::~Book() { cout << "Destroying Book: " << title << endl; } void Book::printAuthorName() { } int main() { // create a Book and an Author shared_ptr< Book > bookPtr(new Book("C++")); shared_ptr< Author > authorPtr(new Author("book2s.com")); bookPtr->weakAuthorPtr = authorPtr; authorPtr->weakBookPtr = bookPtr; bookPtr->sharedAuthorPtr = authorPtr; authorPtr->sharedBookPtr = bookPtr; cout << "Reference count for Book " << bookPtr->title << " is " << bookPtr.use_count() << endl; cout << "Reference count for Author " << authorPtr->name << " is " << authorPtr.use_count() << "\n" << endl; cout << "\nAccess the Author's name and the Book's title through " << "weak_ptrs." << endl; bookPtr->printAuthorName(); authorPtr->printBookTitle(); cout << "Reference count for Book " << bookPtr->title << " is " << bookPtr.use_count() << endl; cout << "Reference count for Author " << authorPtr->name << " is " << authorPtr.use_count() << "\n" << endl; cout << "The shared_ptrs are going out of scope." << endl; }