简体   繁体   English

将 const char* 转换为 char*

[英]Convert const char* into a char*

I'm always wondering about the complaint of the compiler when I declare and define a char*-variable.当我声明和定义一个 char* 变量时,我总是想知道编译器的抱怨。

char* myChar = "Char";

The compiler will complain that it cannot convert const char* to char*.编译器会抱怨它不能将 const char* 转换为 char*。 It need an explicit conversion like它需要像这样的显式转换

char* myChar = (char*)"Char";

My first question is if this is the correct way to initialize a char* with a const char*.我的第一个问题是这是否是用 const char* 初始化 char* 的正确方法。 And my second question is, why the compiler need this explicit conversion.我的第二个问题是,为什么编译器需要这种显式转换。 I think there is no great difference between const char* and char* except the const.我认为 const char* 和 char* 之间没有太大区别,除了 const。

On a technical level, there is a great difference between const MyType* and MyType* and it is easier to see in your example char* myChar = "Char";在技术层面上, const MyType*MyType*之间存在很大差异,在您的示例中更容易看到char* myChar = "Char"; in that the litteral string can be part of memory that may not be changed, but by assigning that to a non-const pointer, you say that you may well planning to change some characters anyway.因为 litteral 字符串可以是 memory 的一部分,可能不会更改,但是通过将其分配给非常量指针,您说您可能会计划更改某些字符。 That behavior is undefined.这种行为是未定义的。 It may work and it may make your program stop unexpectedly and you can't even rule out any other behavior.它可能会起作用,它可能会使您的程序意外停止,您甚至不能排除任何其他行为。

By casting (prefer const_cast in C++), you are saying to the compiler that you know what you're doing and you know better.通过强制转换(更喜欢 C++ 中的const_cast ),您是在对编译器说您知道自己在做什么,而且您知道得更多。 The normal solution is const char* myChar = "Char";正常的解决方案是const char* myChar = "Char"; or even const char* const myChar = "Char";甚至const char* const myChar = "Char"; if you're not planning to point to other char arrays.如果您不打算指向其他字符 arrays。

In C++, I find it even clearer working with std::string if you want to work with strings.在 C++ 中,如果您想使用字符串,我发现使用std::string会更加清晰。

To the advanced programmer, there is definitely a great difference between const and non-const, in terms of integrity, security, and performance.对于高级程序员来说,在完整性、安全性和性能方面,const 和 non-const 之间肯定存在很大差异。 We basically use const when we want to emphasize that a particular object/function/variable isn't allowed to be changed by the user.当我们想要强调不允许用户更改特定对象/函数/变量时,我们基本上使用 const。

check const correctness检查const 正确性

The best-practice way to add/remove const/volatile modifiers is by using const_cast operator.添加/删除 const/volatile 修饰符的最佳实践方法是使用 const_cast 运算符。

check The const_case operator检查const_case 运算符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM