There is a code following code.
#pragma once #include <string> #include <iostream> using namespace std; class TestObject { public: TestObject() : st("default") { cout << st << " is created" << endl; } TestObject(const string& s) : st(s) { cout << st << " is created" << endl; } string ToString() { return st; } void Print() { cout << st << "... printed itself" << endl; } ~TestObject() { cout << st << " is destroyed" << endl; } private: string st; public: static TestObject& null() { static TestObject to("null"); return to; } }; TestObject& test() { TestObject to("Local"); return to; return TestObject::null(); } int main() { test().Print(); cout << endl; system("pause"); return 0; } If you run this code in Debug mode, an error occurs, which is understandable, since the function returns a reference to a local object.
However, if run in Release mode, then everything works and the following output is obtained:
Local is created Local is destroyed ... printed itself Для продолжения нажмите любую клавишу . . . Which is a bit strange.
In addition, if you call test().Print(); twice in a row, an exception will be generated on the first call and the program will stop.
I had the misfortune to make a similar mistake in a real project, and, having assembled a program under Release, I wondered for a very long time why the function returns an empty default value, which I found out in this example, it is not at all. Under the debugger in Release, it is as if return TestObject::null(); , although not null is printed, but just an empty string.
Explain, please, what exactly happens in Release mode.
Following the advice of @Harry, I ran the following code:
TestObject &t = test(); TestObject::null().Print(); t.Print(); At first, a lot of delirium was brought out and the jerky sounds of "pi, pi, pi" began to be generated, after which VS stopped the program with an error reading someone else's memory, but the sound stopped only when he pressed "Abort". All subsequent attempts to run the code ended with the program stopping with the following output.
Local is created Local is destroyed null is created null... printed itself |√& √*Ф ·в┬│ L√& j3╪u р¤~М√& ☻Щлw р¤~`Я·k р¤~ X√& ┼Xпw╠вv∟ д√& ╒Шлw°$Ф р¤~ °$Ф р¤~
Вызвано исключение по адресу 0x0F9165F6 (msvcp140d.dll) в ModernTests.exe: 0xC0000005: нарушение прав доступа при чтении по адресу 0xCCCCCCCC.- this. What happens when you debug or calltest().Print();Twice in a row - RussCoder