#include "stdafx.h" #include <iostream> using namespace std; class MyArray { int *ptrarray; //массив int count; //количество элементов bool check_index(int index); //Проверка на выход за пределы массива public: MyArray(int n) { cout<< "Тут сработал конструктор!\n"; count = n; ptrarray = new int [count]; } MyArray() { cout<< "Тут сработал конструктор!\n"; count =0; ptrarray = NULL; } ~MyArray() { delete [] ptrarray; cout<< "Тут сработал деструктор "<<"\n"; } int get_num(int index); //Получение элемента массива void set_num(int index, int num); //Внесение элемента в массив void create_array(int n); //Инициализация массива через метод int get_count(); //Получить значение количества элементов void fill_array(); //Заполнить масив void print_array(); //Вывести масив void print_num(); //Вывести определенный элемент void arr_addition(MyArray obj1, MyArray obj2); //Поэлементное сложение массивов }; void MyArray::create_array(int n) { count = n; ptrarray = new int [count]; } int MyArray::get_count() { return count; } void MyArray::fill_array() { for (int i = 0; i < count; i++) cin>>ptrarray[i]; } void MyArray::print_array() { for (int i = 0; i < count; i++) cout<<ptrarray[i]<<endl; cout<<endl; } void MyArray::print_num() { int index; cout<<"Введите индекс нужного вам элемента, index= "; cin>>index; if(check_index(index)) cout<<"Значение выбранного вами элемента = "<<get_num(index)<<endl; else cout<<"ОШИБКА! Выбранный индекс выходит за пределы массива!"<<endl; } bool MyArray::check_index(int index) { --index; if((index<count)&&(index>=0)) return true; else return false; } int MyArray::get_num(int index) { --index; return(ptrarray[index]); } void MyArray::set_num(int index, int num) { if(check_index(index)) ptrarray[index] = num; } void MyArray::arr_addition(MyArray obj1, MyArray obj2) { if(obj1.get_count() != obj2.get_count()) cout<<"ОШИБКА! Границы индексов у массивов неодинаковые!"<<endl; else { create_array(obj1.get_count()); for (int i = 0; i < count; i++) { ptrarray[i] = obj1.get_num(i+1) + obj2.get_num(i+1); } } } int _tmain() { setlocale(LC_ALL, "Russian"); int n; cout<<"Введите размер массива, n= "; cin>>n; MyArray arr1(n); //Создаем массив 1 MyArray arr2(n); //Создаем массив 2 arr1.fill_array(); //Заполняем массив 1 arr1.print_array(); //Выводим массив 1 arr2.fill_array(); //Заполняем массив 2 arr2.print_array(); //Выводим массив 2 MyArray arr3; //Создаем массив 3 arr3.arr_addition(arr1, arr2); //Заполняем массив 3 поэлементным сложением массива 1 и 2 arr3.print_array(); //Выводим массив 3 arr1.print_array(); //Выводим массив 1 arr2.print_array(); //Выводим массив 2 system("PAUSE"); return 0; } 

As far as I know, the occupied memory is usually freed in the destructor. What I am doing. But doing something wrong. I still have to continue working with arrays 1 and 2, and the destructor has already cleaned them. And naturally, when I bring them out at the end, any nonsense is displayed. How to be?

  • one
    Vanguyu is the missing copy constructor. I did not read the code. - VladD
  • 2
    well, two “early” destructors are called inside the arr3.arr_addition(arr1, arr2); method arr3.arr_addition(arr1, arr2); I would recommend giving parameters to this method by reference (or by pointer) void MyArray :: arr_addition (MyArray & obj1, MyArray & obj2) like this works as it should - velial
  • one
    VladDb: D I didn’t even know what it was. Googled I delve into it. As far as I understand your prediction is correct)) Thank you - CyberGudvin

2 answers 2

In the void MyArray::arr_addition(MyArray obj1, MyArray obj2) you pass obj1 and obj2 by value. This means that you are copying these objects. So when copying you copy and pointers to the arrays created earlier. Then, when exiting from arr_addition obj1 and obj2 objects are deleted, that is, their destructors are executed in which arrays are deleted.

The solution to the problem is to implement a constructor and a copy operator, in which the "deep" copying of the array is performed.

  • one
    In this case, it will still be easier to transfer objects by reference - Andrio Skur
  • @AndrioSkur: Well, yes. But the question is not how to do it so that it does not fly out. The question is how to do it right. And it is correct either to implement the copy constructor, or to prohibit it. And leave the class with a broken copy constructor - fi. - VladD

You are copying arrays in arr_addition, after the lifetime of the copies ends the original array is prematurely released. You need to override or disable the copy constructor, and pass arrays by reference.

Read the rule of three - https://ru.wikipedia.org/wiki/%D0%9F%D1%80%D0%B0%D0%B2%D0%B8%D0%BB%D0%BE_%D1%82%D1 80% D1% 91% D1% 85_ (C% 2B% 2B_% D0% BF% D1% 80% D0% BE% D0% B3% D1% 80% D0% B0% D0% BC% D0% BC% D0 % B8% D1% 80% D0% BE% D0% B2% D0% B0% D0% BD% D0% B8% D0% B5)