This is question about difference between STL implementations in handling const copy of std::string
. I have such short test, which does 2 const copies and prints addresses returned by c_str()
:
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
string a("Hello World!");
const string b(a);
const string c(b);
printf("a: %p = %s\n", a.c_str(), a.c_str());
printf("b: %p = %s\n", b.c_str(), b.c_str());
printf("c: %p = %s\n", c.c_str(), c.c_str());
return c.c_str() == b.c_str();
}
On my gcc 4.6.2 with libstdc++.so.6.0.16 STL all pointers are returned as equal.
Can I rely on this behaviour?
Is it portable or defined in recent standard?
Will this work on current or future versions of libstdc++, libc++, Microsoft STL, stdcxx (apache.org)?
You can't rely on that behavior at all. The only thing you're guaranteed with respect to c_str()
is that the pointer returned is valid until the underlying string
is mutated (specific methods/feature invalidate the returned pointer). You have no guarantee it will work on any particular architecture or compiler and shouldn't rely on such behavior.