为什么我在将字符串文字转换为 char* 时收到编译器警告,这很糟糕吗?
因此编译器告诉我这是从字符串文字到 char* 的不推荐转换:
char* myString = "i like declaring strings like this";
我应该担心这个吗?这是错误的方法吗?
我需要将 myString
传递给接受 char*
的函数,如果没有此转换,我应该由谁正确初始化 char*
?
So the compiler tells me this is a deprecated conversion from a string-literal to char*:
char* myString = "i like declaring strings like this";
Should I be worried about this? Is this the wrong way to do this?
I need to pass myString
to a function that accepts a char*
, who should I properly initialize the char*
without this conversion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,你应该担心它!
您应该将其声明为:
mystring
是指向字符串文字的指针“我喜欢这样声明字符串”
,并且字符串文字驻留在内存空间中(实现定义) 不应被您的程序修改。修改字符串文字会导致未定义的行为。
因此,C++03 标准不推荐在声明字符串时不使用关键字 const,这确保了字符串不能通过指针修改。
@Benjamin 在评论中已经发布了您的问题编辑的答案,只需引用他的答案:
Yes, You should be worried about it!
You should be declaring it as:
mystring
is an pointer to the string literal"i like declaring strings like this"
, and the string literal resides in an memory space(Implementation Defined) which should not be modified by your program.Modifying a string literal results in Undefined behavior.
Hence, C++03 Standard deprecated declaring string literals without the keyword
const
, This ensures that the string literal cannot be modified through the pointer.Answer to your Question Edit, is already posted by @Benjamin in comments, simply quoting his answer:
它甚至不应该编译。如果您需要将其传递给您确定不会更改字符串的函数,则需要使用 const 强制转换,这是其正确用途之一:
或者,如果您不希望使用 const 强制转换,则可以将字符串复制到堆:
It shouldn't even compile. If you need to pass it to function that you are sure won't change the string you need to use const cast, its one of its correct uses:
Or if you don't want the const cast, you can copy the string to the stack: