What am I missing here? This is really irritating!
Essentially, in main() t.p3()
ALWAYS produces random garbage as if the pointer is invalid, yet everything else ALWAYS works! I determined that the difference is in the length of the string. What voodoo is this?
How do I get t.p3()
to work?
#include <string>
#include <iostream>
static const std::string STRING1( "xxxxxxxxxxxxxxx" );
static const std::string STRING2( "xxxxxxxxxxxxxxxx" ); // MAGIC 16 characters
struct Test
{
std::string string1() const { return STRING1; }
std::string string2() const { return STRING2; }
const char * p1() const { return STRING1.c_str(); }
const char * p2() const { return STRING2.c_str(); }
const char * p3() const { return string1().c_str(); }
const char * p4() const { return string2().c_str(); }
};
int main(int argc, char *argv[])
{
Test t;
std::cout << t.p1() << std::endl; // works
std::cout << t.p2() << std::endl; // works
std::cout << t.p3() << std::endl; // random garbage
std::cout << t.p4() << std::endl; // works
return 0;
}