The compiler says 2, but in theory we refer to one memory area three times.

#include <iostream> #include <cstring> #include <cstdlib> using namespace std; class sample { char *s; public: sample() { s = 0; } ~sample() { if(s) delete [] s; cout << "Освобождение s-памяти.\n"; } void show() { cout << s << "\n"; } void set(char *str); }; // Загрузка строки. void sample::set(char *str) { s = new char[strlen(str)+1]; strcpy(s, str); } //Эта функция возвращает объект типа sample. sample input() { char instr[80]; sample str; cout << "Введите строку: "; cin >> instr; str.set(instr); return str; } int main() { sample ob; // Присваиваем объект, возвращаемый // функцией input(), объекту ob. ob = input(); // Эта инструкция генерирует ошибку(или вывод мусор) ob.show(); // Отображение "мусора". return 0; } 
  • To begin with, your program will free the same memory twice - so UB ... - Harry
  • @Harry I know, I consider potential problems when returning objects. But the question is the same. How many times is the destructor called? - MickeyUL

2 answers 2

In main , an empty object is created. In input, we construct a class; when returning, we make a temporary copy of the stack. At the end of the input method, the local variable str is called. The temporary copy becomes illiquid due to the fact that the string s points to a remote memory location. Further in main you copy a non-liquid temporary object. This temporary object is deleted. The temporary object destructor collapses due to the fact that the line has already been deleted. And if the move reached the main, the destructor would be called again (third) in main . For all the same deleted line, there would be a problem. In about two or three times the destructor was called may be a vague topic of compiler optimization. From input, you pass a local variable. And the compiler can optimize: do not delete twice. Answer: when optimizing two destructors, without optimizing three.

  • Explained as it should. Excellent - MickeyUL

Two (object str in input() and ob in main() ).

But keep in mind that you have copying and assignment - small, so you do not have a program, but a solid problem ...

  • So, and at sample() { s = 0; } sample() { s = 0; } destructor is not called right away? A little swim in this thread just - MickeyUL
  • Just what copy and assignment mean are small ? - MickeyUL
  • one
    In addition to all this, if you call the set method more than once, there will be a memory leak. - LLENN
  • one
    1. No, there is no destruction of the object. 2. Small - it means that they copy your pointer to the allocated memory space. And in the destructor, each object diligently frees the same memory — which is lousy. You must allocate a new memory and copy the contents there (deep copy-assignment). Well, and do not forget to delete the old memory - otherwise, as rightly indicated, the set will be a memory leak. - Harry
  • one
    @MickeyU About copying and assignment: en.cppreference.com/w/cpp/language/rule_of_three - HolyBlackCat