C++ 警告:从字符串文字转换为';字符*';不赞成
在下面的(C++)代码中C++ 警告:从字符串文字转换为';字符*';不赞成,c++,string,C++,String,在下面的(C++)代码中 char * type = ""; switch (mix_mode) { case GO_HISTORY_VIDEO_MIX_VISUAL_GAS: type = "visual gas"; break; case GO_HISTORY_VIDEO_MIX_VISUAL: type = "visual"; br
char * type = "";
switch (mix_mode) {
case GO_HISTORY_VIDEO_MIX_VISUAL_GAS:
type = "visual gas";
break;
case GO_HISTORY_VIDEO_MIX_VISUAL:
type = "visual";
break;
case GO_HISTORY_VIDEO_MIX_GAS:
type = "gas";
break;
case GO_HISTORY_VIDEO_MIX_LARGE_IR_DIRECT:
type = "ir direct";
break;
case GO_HISTORY_VIDEO_MIX_LARGE_IR_FILTERED:
type = "ir filtered";
break;
}
strcpy(suffix, "avi");
snprintf(filename, sizeof(filename), "%s - (%s %s).%s", name_comp, type, uid, suffix);
我有以下警告:
GO_C_MSDExportManager.cpp:192:31: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
char * type = "";
^
GO_C_MSDExportManager.cpp:195:12: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
type = "visual gas";
^
GO_C_MSDExportManager.cpp:198:12: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
type = "visual";
^
GO_C_MSDExportManager.cpp:201:12: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
type = "gas";
^
GO_C_MSDExportManager.cpp:204:12: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
type = "ir direct";
^
GO_C_MSDExportManager.cpp:207:12: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
type = "ir filtered";
我看到char指针是不安全的,但我不确定在这种情况下是否会出现问题,而type
没有在任何其他地方使用
我确实学到了做一些事情的可能性,比如*type='X'
会很糟糕,因为它会改变字符串文字并可能使我的机器崩溃
问题:
char指针会出什么问题
Isconst char*type=new char[20]
消除警告的好方法?的类型是const char[]
,请注意:
在C语言中,字符串文字的类型为char[],可以直接分配给(非常量)char*。C++03也允许这样做(但不赞成这样做,因为C++中的文本是常量)。C++11不再允许这种没有强制转换的赋值
然后
1.字符指针可能出现什么问题
正如您所说,char*
可以更改字符串文字并导致UB
您可以创建一个从字符串文字初始化的数组,然后稍后修改该数组,例如:
char type[] = "something"; // type will contain a copy of the string literal
2.Is const char*type=new char[20];摆脱警告的好办法
无需在此处创建新数组,因为您只是更改指针本身的值,而不是它指向的内容。您只需将type
的类型更改为const char*
const char * type = "";
更改:
char * type = "";
致:
这是因为:”
(同样适用于其他文字)是数组类型的字符串文字。在本例中,它是常量字符[1]
要检查它,可以使用编译器错误技巧:
template<typename T> struct TD;
int main() {
TD<decltype("")> ff;
}
模板结构TD;
int main(){
TD-ff;
}
产出:
main.cpp:10:22: error: aggregate 'TD<const char (&)[1]> ff' has incomplete type and cannot be defined
TD<decltype("")> ff;
main.cpp:10:22:错误:聚合“TD ff”的类型不完整,无法定义
TD-ff;
其中常量字符[1]
是“
的类型,其大小为1,因为它只保留空字符:'\0'
您可以将其分配并用作const char*
,因为数组会衰减为指向其第一个元素的指针。const char*type=“”代码>。
main.cpp:10:22: error: aggregate 'TD<const char (&)[1]> ff' has incomplete type and cannot be defined
TD<decltype("")> ff;