VS 2017 Doesn't Implicitly Convert const char* to char* [duplicate]

Deadly 提交于 2021-01-02 07:00:35

问题


I recently installed VS 2017, and have ran into a weird sort of issue. Basically, I cannot use hard-coded strings without explicitly casting them to (char*). If I said something like Function("test"), it would simply throw an error stating that const char* is incompatible with char*. I really don't want to stick with VS 2015 :(. Anybody know how to make VS recognize that these are the same thing?

Thanks a lot in advance.


回答1:


VisualStudio 2017 15.5 started setting the /permissive- flag for all new solutions, which disallows the implicit conversion of string literals to non-const char*. You can edit the solution's properties to disable that flag while you update your codebase to conform to the C++ standard. It's listed as "Conformance mode" in the "Language" tab under "C/C++" in the project's properties.




回答2:


You shouldn't assign or cast string literals to char*, because it's illegal to modify a string literal, even through a pointer to non-const char.

The incorrect behavior where string literals can be implicitly converted to char* was allowed, but deprecated, in the C++98 (and C99) standards, but removed in the C++11 and C11 standards.

Assigning a string literal to an array variable has value (copy) semantics, as opposed to the reference semantics of pointer variables, so you can assign a string literal to an array of non-const char, and modify that.

char mutable_string[] = "tha string";
mutable_string[2] = 'e'; // OK

Array variables are more useful than pointer variables because they preserve size information at compile-time, so it's better to define an immutable C string like

constexpr char immutable_string[] = "the immutable string";


来源:https://stackoverflow.com/questions/48554625/vs-2017-doesnt-implicitly-convert-const-char-to-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!