[ create a new paste ] login | about

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

johannes - C++, pasted on Sep 27:
class PimplPrivate
{
public:
    PimplPrivate()
        : count(1)
    {
        memset(data, '0', 1024);
    }   
 
    ~PimplPrivate() {}   
 
    PimplPrivate(const PimplPrivate &other)
        : count(1)
    {
        std::copy(other.data, other.data + 1024, data);
    }   
 
    char data[1024];
    int  count;
};
 
class Pimpl
{
public:
    Pimpl()
        : d(new PimplPrivate)
    {
    }   
 
    ~Pimpl()
    {
        if (!d)
            return;
        --d->count;
        if (0 == d->count) {
            delete d;
            d = 0;
        }
    }   
 
    Pimpl(const Pimpl &other)
        : d(other.d)
    {
        ++d->count;
    }   
 
    Pimpl &operator =(const Pimpl &other)
    {
        if (this != &other) {
            --d->count;
            if (0 == d->count)
                delete d;
            d = other.d;
            ++d->count;
         }
         return *this;
    }   
 
    void setData(int i, char value)
    {
        d->data[i] = value;            // crude implementation
    }                                  // for testing purposes only
 
    char data(int i) const
    {
        return d->data[i];             // crude implementation
    }                                  // for testing purposes only
 
private:
    PimplPrivate *d;
};

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


Output:
1
2
3
4
0
0
x
x


Create a new paste based on this one


Comments: