警告:不建议从字符串常量转换为“char*”
我使用库中的以下函数,但无法更改:
HRESULT DynamicTag(char * pDesc, int * const pTag );
我按如下方式使用它。我已经创建了实现上述功能的库提供的类的对象。
int tag =0;
g_pCallback->DynamicTag("MyLogger", &tag);
我收到以下警告:
warning: deprecated conversion from string constant to 'char*'
摆脱上述警告的最佳方法是什么?我不想动态分配内存。
信息:我使用的是Vxworks6.8编译器
Possible Duplicate:
How to get rid ofdeprecated conversion from string constant to ‘char*’
warnings in GCC?
I use following function from library which i cannot change:
HRESULT DynamicTag(char * pDesc, int * const pTag );
I use it as follows. I have created the object of the class provided by the library that implements the above function.
int tag =0;
g_pCallback->DynamicTag("MyLogger", &tag);
I am getting following warning:
warning: deprecated conversion from string constant to 'char*'
What is the best way of getting rid of above warning? I don't want to allocate memory dynamically.
Info: I am using Vxworks6.8 compiler
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
处理未知库
当传递文字而不是其他 const 字符串时,并且您不确定库是否正在修改字符串,很容易在 C++ 中创建文字的堆栈分配临时副本(受到 如何摆脱GCC 中“已弃用从字符串常量到 'char*' 的转换”警告?):
使用显式转换来解决弱库原型
在大多数编译器上,显式转换避免警告,例如:
注意:只有当您确定该函数确实从不修改传递的字符串时(即当该函数可以声明为 const char * 时,但事实并非如此,可能是因为库编写者忘记了),您才能使用此选项添加它)。尝试修改字符串文字是一种未定义的行为,在许多平台上它会导致崩溃。如果您不确定,则需要制作字符串的可写副本,当您知道字符串大小的一些上限时,该副本可能是动态分配的,甚至是堆栈分配的。
Dealing with unknown library
When passing literals and not other const string, and you are not sure if the library is modifiying the string, is easy to create a stack allocated temporary copy of the literal in C++ (inspired by How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?):
Use explicit cast to work around a weak library prototype
On most compilers explicit conversions avoid warnings, like:
Note: You can use this only when you are sure the function is really never modifying the string passed (i.e. when the function could be declared as const char *, but it is not, perhaps because the library writer has forgotten to add it). An attempt to modify a string literal is an undefined behaviour and on many platforms it results in a crash. If you are not sure, you need to make a writeable copy of the string, which may be dynamically allocated or even stack allocated, when you know some upper limit for the string size.
由于您无法更改
DynamicTag
,因此您必须更改调用它的方式。例如,您可以使用:鉴于 pDesc 被声明为 [in] 参数,这意味着它可能不会被更改,因此您可能会摆脱 const,但这是一个坏习惯。
Given you can't change
DynamicTag
, you have to change the way you call it. You can use, for instance:Given pDesc is declared as an [in] argument means it would probably not be changed, so you might get away with casting the const away, but that's a bad habit.
将该值作为数组传递。
Pass that value as an array.