[ create a new paste ] login | about

Link: http://codepad.org/NUyL73z5    [ raw code | output | fork ]

johannes - C++, pasted on Sep 27:
#include <boost/shared_ptr.hpp>
 
class SmartPimplPrivate
{
public:
    SmartPimplPrivate()
    {
        memset(data, '0', 1024);
    }   
 
    ~SmartPimplPrivate() {}   
 
    SmartPimplPrivate(const SmartPimplPrivate &other)
    {
        std::copy(other.data, other.data + 1024, data);
    }   
 
    char data[1024];
};
 
class SmartPimpl
{
public:
    SmartPimpl()
        : d(new SmartPimplPrivate)
    {
    }   
 
    void setData(int i, char value)
    {
        detach();                       // Copy on write
        d->data[i] = value;
    }   
 
    char data(int i) const
    {
        return d->data[i];
    }   
 
    void detach()
    {
        if (d.use_count() > 1) {
            d = boost::shared_ptr<SmartPimplPrivate>(new SmartPimplPrivate(*d));
            std::cout << "---- detaching! ----\n";
        }
    }
 
private:
    boost::shared_ptr<SmartPimplPrivate> d;
};

int main(int argc, char **argv)
{
    SmartPimpl p1;
    p1.setData(0, 'y');
    SmartPimpl p2(p1);
    SmartPimpl p3(p1);
    std::cout << p1.data(0) << "\n";
    std::cout << p2.data(0) << "\n";
    std::cout << p3.data(0) << "\n";
    p1.setData(0, 'x');
    std::cout << p1.data(0) << "\n";
    std::cout << p2.data(0) << "\n";
    std::cout << p3.data(0) << "\n";
    return 0;
}


Output:
1
2
3
4
5
6
7
y
y
y
---- detaching! ----
x
y
y


Create a new paste based on this one


Comments: