C++ examples for Data Type:shared_ptr
Reference Counted shared_ptr
#include <string> using namespace std; class Book //from w w w.j a va2s. c o m { public: Book( const string &bookTitle ); // constructor ~Book(); // destructor string title; // title of the Book }; // Member-function definitions for class Book. #include <iostream> #include <string> using namespace std; Book::Book( const string &bookTitle ) : title( bookTitle ) { } Book::~Book() { cout << "Destroying Book: " << title << endl; } // end of destructor #include <algorithm> #include <iostream> #include <memory> #include <vector> using namespace std; typedef shared_ptr< Book > BookPtr; // shared_ptr to a Book void deleteBook( Book* book ) { cout << "Custom deleter for a Book, "; delete book; // delete the Book pointer } bool compareTitles( BookPtr bookPtr1, BookPtr bookPtr2 ) { return ( bookPtr1->title < bookPtr2->title ); } int main() { BookPtr bookPtr( new Book( "C++" ) ); cout << "Reference count for Book " << bookPtr->title << " is: " << bookPtr.use_count() << endl; // create another shared_ptr to the Book and display reference count BookPtr bookPtr2( bookPtr ); cout << "Reference count for Book " << bookPtr->title << " is: " << bookPtr.use_count() << endl; bookPtr2->title = "Java"; cout << "The Book's title changed for both pointers: " << "\nbookPtr: " << bookPtr->title << "\nbookPtr2: " << bookPtr2->title << endl; // create a std::vector of shared_ptrs to Books (BookPtrs) vector< BookPtr > books; books.push_back( BookPtr( new Book( "C" ) ) ); books.push_back( BookPtr( new Book( "VB" ) ) ); books.push_back( BookPtr( new Book( "C#" ) ) ); books.push_back( BookPtr( new Book( "C++" ) ) ); // print the Books in the vector cout << "\nBooks before sorting: " << endl; for ( int i = 0; i < books.size(); ++i ) cout << ( books[ i ] )->title << "\n"; // sort the vector by Book title and print the sorted vector sort( books.begin(), books.end(), compareTitles ); cout << "\nBooks after sorting: " << endl; for ( int i = 0; i < books.size(); ++i ) cout << ( books[ i ] )->title << "\n"; // create a shared_ptr with a custom deleter cout << "\nshared_ptr with a custom deleter." << endl; BookPtr bookPtr3( new Book( "Small C++ How to Program" ), deleteBook); bookPtr3.reset(); // release the Book this shared_ptr manages // shared_ptrs are going out of scope cout << "\nAll shared_ptr objects are going out of scope." << endl; }