Boost logo

Boost Users :

From: Pavel Antokolsky aka Zigmar (zigmar_at_[hidden])
Date: 2005-04-28 10:07:15


The boost::scopted_ptr is the best way to implement this. No need for
shared_ptr because pimpl is usually not shared (until you implement
some kind of lazy copy-on-write, where shared_ptr _is_ very useful).
It can be also implemented with std::auto_ptr but it more dangerous,
because it will pass the compilation if you forget to implement copy
constructor and operator=(). In that case, the results will be
disastrous - I guess anyone remembers what auto_ptr's copy operator
does...

And another pitfal with both auto_ptr and shared_ptr (at least on
VC7.1 compiler) is if you don't provide expicit destructor, the
generated destructor will try destroy the auto_ptr, which in its turn
will try to destroy you pimpl via imcomplete pointer, therefor not
calling destructor. Fortunately compiler at least gives a warning:
"deletion of pointer to incomplete type 'TestClass::PrivateData'; no
destructor called"

Just a small sniplet of working pimpl implementation with shared_ptr:

header file:

---
class TestClass
{
public:
    TestClass();
    virtual ~TestClass(void);
    TestClass(const TestClass& other);
    TestClass& operator=(const TestClass& other);
private:
    class PrivateData;
    boost::scoped_ptr<PrivateData> pd;
};
implementation file:
---
class TestClass::PrivateData
{
//....
};
TestClass::TestClass()
:pd(new PrivateData)
{
}
TestClass::TestClass(const TestClass& other)
:pd(new PrivateData(*other.pd))
{
}
TestClass& TestClass::operator=(const TestClass& other)
{
    pd.reset(new PrivateData(*other.pd));
    return *this;
}
On 4/27/05, David Gruener <gruenedd_at_[hidden]> wrote:
> Hi,
> i'm wondering if there is a nice smart pointer in boost
> to implement PImpl. I found an implementation here: [1].
> So, does boost provide a smart pointer which does
> play nice with pimpl, so that one doesn't need to provide
> a destructor, copyconstructor and assignment operator
> for the default cases?
> 
> --David
> 
> [1]
> http://www.octopull.demon.co.uk/arglib/TheGrin.html.
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
> 
-- 
Best regards,
Zigmar

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net