Modifying underlying char array of a c++ string ob

2020-06-12 05:09发布

My code is like this:

string s = "abc";
char* pc = const_cast<char*>( s.c_str() );
pc[ 1 ] = 'x';
cout << s << endl;

When I compiled the snippet above using GCC, I got the result "axc" as expected. My question is, is that safe and portable to modify the underlying char array of a C++ string in this way? Or there might be alternative approaches to manipulate string's data directly?

FYI, my intention is to write some pure C functions that could be called both by C and C++, therefore, they can only accept char* as arguments. From char* to string, I know there is copying involved, the penalty is unfavorable. So, could anybody give some suggestions to deal with this sort of situation.

7条回答
Ridiculous、
2楼-- · 2020-06-12 06:09

The obvious answer is no, it's undefined behavior. On the other hand, if you do:

char* pc = &s[0];

you can access the underlying data, in practice today, and guaranteed in C++11.

查看更多
登录 后发表回答