C++17 中带有字符串文字的 CLion 警告
CLion warning with string literals in C++17
我在 CLion 中遇到了一个奇怪的行为。我有两个函数将 std::string
和 const std::string&
作为参数。我称他们传递字符串文字。
我尝试过不同版本的 C++:C++17 和 C++14
#include <iostream>
#include <string>
void print(std::string str){
std::cout<<str<<std::endl;
}
void print_ref(const std::string& str){
std::cout<<str<<std::endl;
}
int main() {
print("Hello World!");
print_ref("Hello World!");
return 0;
}
如果代码是 C++17,CLion(或更好的 IntelliSense)会报告此警告 Paramemeter type mismatch: Types 'std::string' and 'const char[13]' are not compatible
,但如果我切换到 C++14,警告就会消失。代码是否正确?
您的环境似乎有问题。在我的情况下工作得很好。
系统配置
CLion
Version 2019.1.3 (CL-191.7141.37)
LLVM
Apple LLVM version 9.0.0 (clang-900.0.39.2)
这似乎是 CLions 代码完成/lint 功能的问题。不知何故,linter 没有意识到虽然 const char[]
和 std::string
不是相同的类型,但 std::string
有一个完全有效的隐式构造函数,这使得这段代码工作得很好。
我不会太介意这些怪癖。作为一般的经验法则,如果您不确定由这些类型的 linter 生成的 warning/error 是否有效,那么只需尝试构建您的项目,如果实际的编译过程只产生错误,那么您的代码在某种程度上是错误的。
我在 CLion 中遇到了一个奇怪的行为。我有两个函数将 std::string
和 const std::string&
作为参数。我称他们传递字符串文字。
我尝试过不同版本的 C++:C++17 和 C++14
#include <iostream>
#include <string>
void print(std::string str){
std::cout<<str<<std::endl;
}
void print_ref(const std::string& str){
std::cout<<str<<std::endl;
}
int main() {
print("Hello World!");
print_ref("Hello World!");
return 0;
}
如果代码是 C++17,CLion(或更好的 IntelliSense)会报告此警告 Paramemeter type mismatch: Types 'std::string' and 'const char[13]' are not compatible
,但如果我切换到 C++14,警告就会消失。代码是否正确?
您的环境似乎有问题。在我的情况下工作得很好。
系统配置
CLion
Version 2019.1.3 (CL-191.7141.37)
LLVM
Apple LLVM version 9.0.0 (clang-900.0.39.2)
这似乎是 CLions 代码完成/lint 功能的问题。不知何故,linter 没有意识到虽然 const char[]
和 std::string
不是相同的类型,但 std::string
有一个完全有效的隐式构造函数,这使得这段代码工作得很好。
我不会太介意这些怪癖。作为一般的经验法则,如果您不确定由这些类型的 linter 生成的 warning/error 是否有效,那么只需尝试构建您的项目,如果实际的编译过程只产生错误,那么您的代码在某种程度上是错误的。