我有 这个按预期工作的代码:
#define MAX_PARAM_NAME_LEN 32
const char* GetName()
{
return "Test text";
}
int main()
{
char name[MAX_PARAM_NAME_LEN];
strcpy(name, GetName());
cout << "result: " << name << endl;
}
如果我想将结果存储到 char *
(因为我使用的框架中的某些功能仅使用 char *
作为输入)而不使用 strcpy
(为了代码的实用性和可读性,以及学习),我该怎么办?保持 const
,这很好用:
const char* name;
name = GetName();
但我仍然有 const
。
试图只使用 char*
:
char* name;
name = GetName();
我得到 invalid conversion from 'const char*' to 'char*'
。这种转换的最佳习惯是什么?
原文由 markzzz 发布,翻译遵循 CC BY-SA 4.0 许可协议
return "Test text";
返回一个指向 只读 字符串 字面 量的指针。如果您使用的函数将
char*
作为输入,并且您有const char*
(例如只读字符串文字),那么您应该提供一个深将从const char*
开始的字符串复制到此类函数。否则,如果函数尝试修改只读字符串,您将面临运行时未定义行为的风险。
你目前拥有的就足够了;假设您不能使用
std::string
。 (如果您 可以 使用std::string
并且 您的所有框架函数都采用const char*
输入,那么我建议您重构代码以使用std::string
,并且将该字符串类上的c_str()
方法的输出传递给您的框架函数。)最后,如果您的某些框架功能需要
char*
那么您总是可以自己构建一个小型适配器类:Then for a function
void foo(char* c)
, you can callfoo(Adapter("Hello"/*or any const char* */));
andfoo
can do as it pleases with thechar*
that’s embedded in the anonymous temporary !您甚至可以增强此类以将构造函数带到char*
在这种情况下,仅获取指针的浅表副本(并且析构函数不会删除内存)。