C++ STL:在创建std :: string的const副本时会改变c_str()吗?

osg*_*sgx 2 c++ stl libstdc++ c-str libc++

这是关于STL实现处理const副本的区别的问题std::string.我有这么短的测试,它执行2个const副本并打印返回的地址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();
}
Run Code Online (Sandbox Code Playgroud)

在我的gcc 4.6.2上使用libstdc ++.so.6.0.16 STL所有指针都返回相等.

我可以依靠这种行为吗?

它是便携式还是最近标准中定义的?

这是否适用于当前或未来版本的libstdc ++,libc ++,Microsoft STL,stdcxx(apache.org)?

Cha*_*via 10

这就是所谓的COW(写入时复制)语义.这是一种避免不必要的字符串复制的优化策略.但是你不能依赖这种行为 - 它是GNU libstdc ++的一个实现细节.实际上,C++ 11标准不允许这样做.