gpt4 book ai didi

c++ - 防止函数接受 const std::string& 接受 0

转载 作者:行者123 更新时间:2023-12-01 17:54:38 24 4
gpt4 key购买 nike

值得一千字:

#include<string>
#include<iostream>

class SayWhat {
public:
SayWhat& operator[](const std::string& s) {
std::cout << s << "\n";
return *this;
}
};

int main() {
SayWhat ohNo;
// ohNo[1]; // Does not compile. Logic prevails.
ohNo[0]; // you didn't! this compiles.
return 0;
}

将数字 0 传递给接受字符串的括号运算符时,编译器不会提示。相反,在进入方法之前会编译并失败:

terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid

供引用:

> g++ -std=c++17 -O3 -Wall -Werror -pedantic test.cpp -o test && ./test
> g++ --version
gcc version 7.3.1 20180303 (Red Hat 7.3.1-5) (GCC)

我的猜测

编译器隐式使用 std::string(0) 构造函数来进入该方法,这会无缘无故地产生相同的问题(谷歌搜索上述错误)。

问题

是否有办法在类端修复此问题,以便 API 用户感觉不到这一点并且在编译时检测到错误?

即添加一个重载

void operator[](size_t t) {
throw std::runtime_error("don't");
}

这不是一个好的解决方案。

最佳答案

std::string(0) 有效的原因是 0 是一个空指针常量。所以 0 匹配带有指针的字符串构造函数。然后,该代码的运行就违反了不得将空指针传递给 std::string 的前提条件。

只有文字 0 才会被解释为空指针常量,如果它是 int 中的运行时值,则不会遇到此问题(因为然后重载分辨率将寻找 int 转换来代替)。文字 1 也不是问题,因为 1 不是空指针常量。

由于这是一个编译时问题(文字无效值),您可以在编译时捕获它。添加此形式的重载:

void operator[](std::nullptr_t) = delete;

std::nullptr_tnullptr 的类型。它会匹配任何空指针常量,无论是00ULL还是nullptr。并且由于该函数被删除,因此在重载解析期间会导致编译时错误。

关于c++ - 防止函数接受 const std::string& 接受 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58909097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com