【发布时间】:2011-10-18 15:39:08
【问题描述】:
我在一个用 C 语言编写的第三方库中有一个函数:char* fix_filename_slashes(char* path)。此函数需要一个可变的 C 字符串传递给它,因此它可以根据操作系统将路径中的所有斜杠更改为正确使用。我在 Facade 中使用的所有字符串都声明为 std::strings。我试图简单地使用foo.c_str(),因为其他所有期望C字符串的函数都不会改变它并且期望const char *,但是这个函数会导致错误:Error: Argument of type "const char *" is incompatible with parameter of type "char *"
是我想出的结果:
char* tempf = const_cast<char*>(filename.c_str());
filename = std::string(fix_filename_slashes(tempf));
tempf = NULL;
认为“正确”还是有其他(更正确?)方法来完成任务?
编辑
哎呀。显然,该函数返回字符串的副本。仍然有一些很好的答案。
【问题讨论】:
-
上面写满了未定义的行为
-
@Gene Bushuyev:你能解释一下 UB,让我知道怎么回事吗?
-
21.3.6 ... const charT* c_str() const; ....“程序不得更改存储在数组中的任何值”