[ create a new paste ] login | about

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

johannes - C++, pasted on Sep 27:
class A
{
public:
    A(const char *info)
        : m_info(new std::string(info))
    {
        std::cout << "allocating object resources\n";
    }
 
    ~A()
    {
        delete m_info;
        std::cout << "deallocating object resources\n";
    }
 
    A(const A &other)
        : m_info(new std::string(*other.m_info))
    {
        std::cout << "copying data\n";
    }
 
    A &operator =(const A &other)
    {
        if (this != &other) {
            delete m_info;
            m_info = new std::string(*other.m_info);
            std::cout << "allocating + copying data\n";
        }
        return *this;
    }
 
    inline std::string info() const { return *m_info; }
 
private:
    std::string *m_info;
};
 
int main()
{
    std::vector<A> v;
 
    A a("banana");
    v.push_back(a);
 
    A b("mayonnaise");
    v.push_back(b);
 
    A c("aardvark");
    v.push_back(c);
 
    std::cout << "------------\n";
 
    std::cout << v.at(0).info() << "\n";
    std::cout << v.at(1).info() << "\n";
    std::cout << v.at(2).info() << "\n";
 
    std::cout << "------------\n";
 
    return 0;
}


Output:
allocating object resources
copying data
allocating object resources
copying data
copying data
deallocating object resources
allocating object resources
copying data
copying data
copying data
deallocating object resources
deallocating object resources
------------
banana
mayonnaise
aardvark
------------
deallocating object resources
deallocating object resources
deallocating object resources
deallocating object resources
deallocating object resources
deallocating object resources


Create a new paste based on this one


Comments: