[ create a new paste ] login | about

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

johannes - C++, pasted on Sep 27:
class Stuff
{
public:
    Stuff()
        : m_count(new long unsigned),
          m_data(new char[1024])
    {
        *m_count = 1;       
 
        // Fill data with '0' character
        memset(m_data, '0', 1024);
    }   
 
    ~Stuff()
    {
        decrement();
    }   
 
    Stuff(const Stuff &other)
        : m_count(other.m_count),
          m_data(other.m_data)
    {
        ++(*m_count);
    }   
 
    Stuff &operator =(const Stuff &other)
    {
        if (this != &other) {
            decrement();
            m_count = other.m_count;
            m_data = other.m_data;
            ++(*m_count);
        }
        return *this;
    }   
 
    void setData(int i, char value)
    {
        m_data[i] = value;            // crude implementation
    }                                 // for testing purposes only
 
    char data(int i) const
    {
        return m_data[i];             // crude implementation
    }                                 // for testing purposes only
 
private:
    void decrement()
    {
        if (!m_count)
            return;
        --(*m_count);
        if (0 == *m_count) {
            delete m_count;
            if (m_data)
                delete[] m_data;
            m_count = 0;
            m_data = 0;
            std::cout << "Deleting data!\n";   // debug info
        }
    }   
 
    unsigned long *m_count;
    char          *m_data;
};

int main(int argc, char **argv)
{
    Stuff obj;
    Stuff obj2(obj);
    Stuff obj3;
    obj3 = obj2;
 
    std::cout << obj.data(5) << "\n";       // '0'
    std::cout << obj2.data(5) << "\n";      // '0'
    std::cout << obj3.data(5) << "\n";      // '0'
 
    obj2.setData(5, 'x');
 
    std::cout << obj.data(5) << "\n";       // 'x'
    std::cout << obj2.data(5) << "\n";      // 'x'
    std::cout << obj3.data(5) << "\n";      // 'x'

    return 0;
}


Output:
1
2
3
4
5
6
7
8
Deleting data!
0
0
0
x
x
x
Deleting data!


Create a new paste based on this one


Comments: