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) {}