我能得到一个非const的C字符串从C ++字符串回来? [英] Can I get a non-const C string back from a C++ string?
问题描述
常量,正确性在C ++中仍然让我头疼。在一些旧的C code的工作,我觉得自己需要分配将一个C ++字符串对象转换为C字符串,并将其分配给一个变量。然而,这个变量是一个的char *
和 c_str()
返回为const char []
。有没有好的办法来解决这个问题,而不必推出自己的功能做呢?
Const-correctness in C++ is still giving me headaches. In working with some old C code, I find myself needing to assign turn a C++ string object into a C string and assign it to a variable. However, the variable is a char *
and c_str()
returns a const char []
. Is there a good way to get around this without having to roll my own function to do it?
编辑:我也在努力避免调用新的。我会很乐意交易稍微复杂一些code较少的内存泄漏。
edit: I am also trying to avoid calling new. I will gladly trade slightly more complicated code for less memory leaks.
推荐答案
我想总会有的strcpy
。
或者使用的char *
串在你的C ++ code的部分必须用旧的东西连接。
Or use char*
strings in the parts of your C++ code that must interface with the old stuff.
或者重构现有的code与C ++编译器编译,然后使用 STD:字符串
Or refactor the existing code to compile with the C++ compiler and then to use std:string
.
这篇关于我能得到一个非const的C字符串从C ++字符串回来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!