2

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)?

osgx
  • 90,338
  • 53
  • 357
  • 513
  • I think this is an implementation detail which you should not rely upon. –  Dec 10 '12 at 17:19
  • It's an implementation detail. Nothing in the language specification states that you can rely on this. You only need to try this out on some different compilers to see that. For example try VS. – David Heffernan Dec 10 '12 at 17:22
  • 3
    Note that COW is prohibited in C++11, since n2668: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2668.htm – ecatmur Dec 10 '12 at 17:24
  • 1
    It does not work in the current nor future versions of libc++. – Howard Hinnant Dec 11 '12 at 00:04

2 Answers2

10

This is what's known as COW (Copy on Write) semantics. It is an optimization strategy to avoid unnecessary copying of strings. But you cannot rely on this behavior - it is an implementation detail of GNU libstdc++. In fact, it is not allowed by the C++11 standard.

Community
  • 1
  • 1
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
3

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.

Mark B
  • 95,107
  • 10
  • 109
  • 188