不推荐从字符串常量转换为char*错误

Deprecated conversion from string constant to char * error

本文关键字:char 错误 转换 常量 字符串      更新时间:2023-10-16

可能重复:
C++不赞成从字符串常量转换为"char*">

我有以下代码,虽然我没有复制完整的代码,因为它是巨大的。以下代码在template类中,我收到如下警告。由于模板中的警告,我无法实例化它,并出现"从这里实例化"错误。

警告:不赞成从字符串常量转换为"char*">

void ErrorMessageInRaphsodyCode(char* pcCompleteMessage, char* pcMessage, char* pcFileName, unsigned int RowNo)
{
//...
}

char cCompleteMessage[200];
memset(cCompleteMessage, 0x00, sizeof(cCompleteMessage));
char*cMessage = "add reorgenize failed";
ErrorMessageInRaphsodyCode(cCompleteMessage, cMessage, "omcollec.h", __LINE__);

我的问题是,消除上述警告的最佳方法是什么?

如果函数采用char const *,它保证只读取指针指向的任何数据。但是,如果它采用像char *这样的非常量指针,它可能会向其写入。

由于写入字符串文字是不合法的,编译器将发出警告。

最好的解决方案是将函数更改为接受char const *而不是char *

char cMessage[] = "add reorganize failed";

这应该可以消除警告。

最好的方法是修复接受参数的函数。

如果您的代码是正确的,并且函数确实使用字符串常量,那么它应该在其原型中这样说:

void ErrorMessageInRaphsodyCode(char* pcCompleteMessage, char* pcMessage, const char* pcFileName, unsigned int RowNo)

如果你不能做到这一点(你没有代码(,你可以创建一个内联包装器:

inline void ErrorMessageInRaphsodyCodeX(char* p1, char* p2, const char* p3, unsigned int p4)
{  ErrorMessageInRaphsodyCode(p1,p2,(char*)p3,p4); }

并使用包装器。

如果您的代码不正确,并且函数确实需要可写内存(我对此深表怀疑(,则需要按照Jan的建议创建一个本地数组,或者malloc提供足够的内存,从而使字符串可写。

(1(使变量成为const char*

(..., const char* pcFileName, ...)

(2(如果以上不可能,并且您希望保留char*const char*的状态,则将函数设为template:

template<typename CHAR_TYPE>  // <--- accepts 'char*' or 'const char*'
void ErrorMessageInRaphsodyCode(char* pcCompleteMessage, CHAR_TYPE* pcMessage, char* pcFileName, unsigned int RowNo)
{
//...
}

函数std::string类的c_str()