A
A B
Hi,
I recently came across this strange behavior (from my point of view)
with C++ strings. I thought it was supposed to be intuitively easy to
use, unlike C-style char arrays. In particular, operator+ was
supposed to concatenate strings on the fly and let the compiler figure
out the low-level details. Here is a short code sample that I tested:
#include <string>
#include <iostream>
using namespace std;
int main() {
const string name("sample");
const string ext("txt");
const char* const srcName = (string("file_") + name + string(".")
+ ext).c_str();
cout << "srcName, when created: " << srcName << endl;
const string trgNameStr = name + string("_1.") + ext;
cout << "srcName, after trgNameStr has been created: " << srcName
<< endl;
const char* const trgName = trgNameStr.c_str();
cout << "trgName, when created: " << trgName << endl;
return 0;
}
Under GCC 4.4.3, this produces
srcName, when created: file_sample.txt
srcName, after trgNameStr has been created: sample_1.txt
trgName, when created: sample_1.txt
So, the mere fact of creating a "target file name" string modifies the
"source file name" string, and makes it equal to the target??? Despite
the fact that everything is constant? This is not the behavior I
expected from my limited C++ knowledge. Could one of the gurus please
clarify?
Thanks
I recently came across this strange behavior (from my point of view)
with C++ strings. I thought it was supposed to be intuitively easy to
use, unlike C-style char arrays. In particular, operator+ was
supposed to concatenate strings on the fly and let the compiler figure
out the low-level details. Here is a short code sample that I tested:
#include <string>
#include <iostream>
using namespace std;
int main() {
const string name("sample");
const string ext("txt");
const char* const srcName = (string("file_") + name + string(".")
+ ext).c_str();
cout << "srcName, when created: " << srcName << endl;
const string trgNameStr = name + string("_1.") + ext;
cout << "srcName, after trgNameStr has been created: " << srcName
<< endl;
const char* const trgName = trgNameStr.c_str();
cout << "trgName, when created: " << trgName << endl;
return 0;
}
Under GCC 4.4.3, this produces
srcName, when created: file_sample.txt
srcName, after trgNameStr has been created: sample_1.txt
trgName, when created: sample_1.txt
So, the mere fact of creating a "target file name" string modifies the
"source file name" string, and makes it equal to the target??? Despite
the fact that everything is constant? This is not the behavior I
expected from my limited C++ knowledge. Could one of the gurus please
clarify?
Thanks