Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Automate Resource Management with shared_ptr-4 : Page 4


advertisement
Pimpl Revisited
shared_ptr can eliminate the hassles of manual memory management when implementing the Pimpl idiom, which I presented here last month. In the header file containing the class' declaration, replace the opaque pointer member with a shared_ptr (the revised code is highlighted):

//++file string.h #include <iosfwd> #include <memory>//for shared_ptr class String { public: String (); ~String(); //... size_t length() const; ostream & operator << (ostream& s) const; //... private: struct StringImpl; //fwd declaration of internal struct shared_ptr <StringImpl> pimpl; //instead of opaque ptr }; In the .cpp file, remove the destructor: //++file string.cpp #include <vector> #include "Lock.h" #include "String.h" struct String::StringImpl { vector <char> vc; size_t len; Lock lck; }; String::String(): pimpl (new String::StringImpl) {}

That's all!



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap