Add:
Sorry, the non-VC compiler bug, is my own error. The return value of ToString () is a temporary string, and the const char* Sztext = const_cast<test&> (TST) is executed. ToString (). C_STR (); The temporary string is destroyed, and the string content pointed to by Sztext has been destroyed, so it is garbled. As for, g++ compiled, the output is correct, it is possible that VC + + and g++ to std::string implementation of different ways (reference: Jackyjkchen answer: GCC string use reference count, write-time copy, it is likely that the different scenarios of the differences in the destructor).
By the way, we remind you to use the C_str method of string carefully.
Reference articles:
1. Carefully use the C_STR () value of the temporary string object
2. The destructor of a temporary object in C + +------Incidentally remind you to use String C_str Method 3 again. C + + C_STR () and temporary variable 4. C + + STRING.C_STR () function of some questions, seek expert help
The day before yesterday, VC2015 compiled the project to appear inexplicable error, after debug, found similar to the following sample code
"Const char* Sztext = const_cast<test&> (TST). ToString (). C_STR (); "Output is not normal, sztext debug view is garbled,
Baffled, had to split the previous code into two lines, the result of the compilation of normal operation. Later in the Windows MinGW (gcc 4.9.2) test,
Found the result is normal. It is estimated that this is a bug in the VC + + compiler.
#include <iostream>
class Test
{public
:
std::string ToString ()
{return
std::string ("Nihao");
}
;
void Test (const test& TST)
{
//write single line, vs2015, sztext result debug to garbled, console output empty
//and MinGW compile output normal
const char* Sztext = const_cast<test&> (TST). ToString (). C_STR ();
Divided into two lines, vs2015 and MinGW output are normal
std::string strText = const_cast<test&> (TST). ToString ();
Const char* SZTEXT2 = Strtext.c_str ();
Std::cout << "Sztext:" << sztext << ' \ n ';
Std::cout << "szText2:" << szText2 << ' \ n ';
}
int main ()
{
Test tst;
Test (TST);
GetChar ();
}
test Environment
System: WIN10 Professional Edition 32bit
Vs:vs Community version 2015 14.0.25431.01 Update3. Compiling the test program 32bit
Gcc:windows gcc4.9.2 Compilation options: g++-std=c++1y. Compiling the test program 32bit
Output results
VS2015
Gcc