clarray.h
#ifndef CLARRAY_H #define CLARRAY_H #include <iostream> #include <QString> using std::cout; using std::cin; using std::endl; class array { private: int* ptr; int size; QString name = "tmp_obj"; public: array(int s, QString name){ size = s; ptr = new int[s]; this->name = name; } array(int s, int* p){ size = s; ptr = p; } ~array(){ cout << "destructor " << name.toStdString() << endl; delete[] ptr; } int& operator[](const int& j){ return *(ptr+j); } array operator=(const array& cl){ if(this!= &cl){ size = cl.size; delete[] ptr; ptr = new int[size]; *ptr = *cl.ptr; // для отладки пусть size == 1 } cout << "= " << *this->ptr << endl; return *this; } }; #endif // CLARRAY_H main.cpp
#include <QCoreApplication> #include <iostream> #include <clarray.h> using std::cout; using std::cin; using std::endl; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); const int ASIZE = 1; array *cl = new array(ASIZE, "c1"); array *c2 = new array(ASIZE, "c2"); for(int i = 0; i < ASIZE; i++) (*cl)[i] = i*i; *c2 = *cl; //сразу после присваивания срабатывает деструктор c2 for(int i = 0; i < ASIZE; i++) cout << "c1: " << (*cl)[i] << " "; cout << endl; for(int i = 0; i < ASIZE; i++) cout << "c2: " << (*c2)[0] << " "; cout << endl; delete cl; delete c2; // return a.exec(); } Output
= 0 destructor c2 c1: 0 c2: -572662307 destructor c1 destructor c2 Another throws the exception _crtisvalidheappointer (block) , as I understand it because of the fact that I am addressing the freed memory.
Question: Why does the destructor work right after assignment?