#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?
CTestoperator = (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;
}