Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
2.67/5 (2 votes)
See more:
C++
// the declaration and definition
class Test
{
private:
    int* p;
public:
    Test(int data)
    {
        p = new int;
        *p = data;
    }
    ~Test()
    {
        delete p;
    }
    Test(const Test& rhs) {}
};
// the main
void main()
{
    Test t1(10);
    Test t2(12);
    Test t3 = t1;
    t2 = t1;
}

How to implement the copy constructor so that the last 2 assignments work well without any memory leak?
Posted

1 solution

The last assignment doesn't call the copy constructor, it calls the assignment operator.


The implementation of the copy constructor and the assignment operator can be something like:


C++
Test(const Test& rhs)
{
    p = new int;
    *p = *rhs.p;
}

Test& operator= (const Test& rhs)
{
    if (!p)
    {
        p = new int;
    }

    *p = *rhs.p;

    return *this;
}

In addition to that, you can consider an implementation of the move constructor and the move assignment operator (C++11) too:


C++
Test(Test&& rhs)
{
    p = rhs.p;
    rhs.p = nullptr;
}

Test& operator= (Test&& rhs)
{
    if (p)
    {
        delete p;
    }

    p = rhs.p;
    rhs.p = nullptr;

    return *this;
}
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900