copy constructor/destructor issues

Hi there. I have code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>

class CTest {
private:
    int m_nData;
public:
    int getData () const {
        return m_nData;
    }

    CTest (int p_nData): m_nData(p_nData) {
        std::cout << "class is created. Data is " << m_nData << std::endl;
    }

    CTest (const CTest & other) {
        std::cout << "class is copied. Data is: " << m_nData << " New data is: " << other.getData() << std::endl;
        m_nData = other.getData();
    }

    CTest operator = (const CTest & other) {
        std::cout << "class is copied via operator. Data is: " << m_nData << " New data is: " << other.getData() << std::endl;
        m_nData = other.getData();
    }

    ~CTest () {
        std::cout << "class is destroyed. Data is " << m_nData << std::endl;
    }
};

CTest res(11);

int main () {
    res= CTest(1);
    res= CTest(2);

    return 0;
}


I wonder why when i execute it two extra destructors are called:

class is created. Data is 11
class is created. Data is 1
class is copied via operator. Data is: 11 New data is: 1
class is destroyed. Data is 4198336
class is destroyed. Data is 1
class is created. Data is 2
class is copied via operator. Data is: 1 New data is: 2
class is destroyed. Data is 4198336
class is destroyed. Data is 2
class is destroyed. Data is 2

What is that? How to overcome it? Should i use shared pointers instead?
Last edited on
Your assignment operator is wrong:

1
2
3
4
5
    CTest operator = (const CTest & other) { // Returns a copy of whatever
        std::cout << "class is copied via operator. Data is: " << m_nData << " New data is: " << other.getData() << std::endl;
        m_nData = other.getData();
// Note: missing return statement
    }


If you want to return something, use a reference:
1
2
3
4
5
    CTest& operator = (const CTest & other) { // Note: &
        std::cout << "class is copied via operator. Data is: " << m_nData << " New data is: " << other.getData() << std::endl;
        m_nData = other.getData();
        return *this;
    }
Now you don't have an extra destruction anymore
Thanks
Topic archived. No new replies allowed.