【发布时间】:2019-10-14 11:23:28
【问题描述】:
我想出了下面的例子,它暴露了一些意想不到的行为。 我希望在 push_back 之后,向量中的任何内容都在那里。 看起来编译器以某种方式决定重用 str 使用的内存。
有人能解释一下这个例子中发生了什么吗? 这是有效的 c++ 代码吗?
最初的问题来自负责序列化/反序列化消息的代码,它使用 const_cast 来删除 constness。 在注意到该代码的一些意外行为后,我创建了这个简化的示例,试图演示该问题。
#include <vector>
#include <iostream>
#include <string>
using namespace std;
int main()
{
auto str = std::string("XYZ"); // mutable string
const auto& cstr(str); // const ref to it
vector<string> v;
v.push_back(cstr);
cout << v.front() << endl; // XYZ is printed as expected
*const_cast<char*>(&cstr[0])='*'; // this will modify the first element in the VECTOR (is this expected?)
str[1]='#'; //
cout << str << endl; // prints *#Z as expected
cout << cstr << endl; // prints *#Z as expected
cout << v.front() << endl; // Why *YZ is printed, not XYZ and not *#Z ?
return 0;
}
【问题讨论】:
-
你确定?像我期望的那样为我打印 XYZ - 因为您没有修改
v的字符串... -
ideone.com/5EnKAZ 不能复制,但这不是
const_cast的用途。 -
我使用了 g++ 5.4.0 和 clang++ 4.0.0。两者都给出相同的结果~~~ ~/tmp$ g++ -std=c++14 x.cpp ~/tmp$ ./a.out XYZ *#Z *#Z *YZ ~~~
-
clang 4.0: godbolt.org/z/SoNVEk g++ 5.4: godbolt.org/z/rE73lI 仍然没有发生。
-
我认为这里没有未定义的行为。只要数据未声明为 const,
const_cast就可以工作。据我所知,std::string不会将其数据存储为 const 数组。
标签: c++ constants stdstring const-cast copy-on-write