advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
"The introduction of shared_ptr makes a built-in garbage collector almost redundant in C++." What is your opinion? Let us know in our C++ Discussion Forum.
Partners & Affiliates
advertisement
advertisement
advertisement
advertisement
Average Rating: 4/5 | Rate this item | 4 users have rated this item.
Automate Resource Management with shared_ptr (cont'd)
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) {}
advertisement
That's all!

Previous Page: Counting on Reference Counting  
Page 1: IntroductionPage 3: Counting on Reference Counting
Page 2: Presenting the ProblemPage 4: Pimpl Revisited
Please rate this item (5=best)
 1  2  3  4  5
advertisement