// Compile OS X: c++ -std=c++11 -stdlib=libc++ SharedPtr.cpp -o SharedPtr // Compile Linux: g++ -std=c++0x SharedPtr.cpp -o SharedPtr #include #include using namespace std; const char infoStr [] = { "INFO: THIS EXAMPLE EXPLAINS HOW TO CREATE SHARED POINTER AND MANIPULATE THEM\n"}; //*********************************************************************************************** class Dealloc { public: Dealloc() {} void operator() (int* p ) { if( p ) { //Do the custom deallocation job cout<<" Dealloc called to release the resource "<( int(10) ); cout<<*sp1<( new int(100) ); //4. Creating shared pointer with a nullptr auto sp5 = shared_ptr(nullptr); if( sp5 == NULL ) { cout<<"Null pointer"<(p); //Uncomment the below lines to get the access violation. /* auto sp2FromRaw = shared_ptr(p); //Notice to get the reference count of either sp1FromRaw or sp2FromRaw. It will give the //count as 1 instead of 2 as they are created from the raw pointer. nbReferences = sp2FromRaw.use_count(); //or sp1FromRaw.use_count(); cout<<" Number of shared pointers sharing the resource = "<(new int(1000), Dealloc() ); auto sp7(sp6); //10. Check how the resource is freed up when the reference count to zero { auto sp8 = shared_ptr( new int[5], [ ](int* p) { cout<<"Releasing array of objects..."<( new Base() ); shared_ptr sp13 = dynamic_pointer_cast(sp12); if( sp13 ) { cout<<"Dynamic casting from 12 to 13 succeeds...."<