Reputation: 71
I'm assuming this is undefined behavior, but I'm not exactly sure why?
When I compile the above code with g++ 4.4.7 and execute it:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string A = "-A";
string B = "_B";
string common = "Common";
const char* commonA = (common + A).c_str();
const char* commonB = (common + B).c_str();
cout << commonA << endl;
cout << commonB << endl;
return 0;
}
The resulting prints show that both commonA and commonB evaluate to "Common_B".
I noticed that when I put the same code into an online c++ ide I get the expected result where commonA is "Common-A" and commonB is "Common_B". Hence why I think what I'm doing is undefined behavior.
I was able to get the original snippet of code to give me the expected behavior in g++ 4.4.7 by separating the string concatenation and c_str() call into two steps. i.e.:
string commonA_str = common + A;
string commonB_str = common + B;
const char* commonA = commonA_str.c_str();
const char* commonB = commonB_str.c_str();
What exactly is going on here, and what is a safe way to do this?
Thanks!
Upvotes: 0
Views: 54