kab*_*nus 80 c++ string std implicit-conversion
值一千字:
#include<string>
#include<iostream>
class SayWhat {
public:
SayWhat& operator[](const std::string& s) {
std::cout<<"here\n"; // To make sure we fail on function entry
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;
}
Run Code Online (Sandbox Code Playgroud)
将数字0传递给接受字符串的方括号运算符时,编译器不会抱怨。相反,它会在输入以下方法之前编译并失败:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
Run Code Online (Sandbox Code Playgroud)
以供参考:
> 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)
Run Code Online (Sandbox Code Playgroud)
我猜
编译器隐式地使用std::string(0)构造函数输入方法,由于没有充分的理由,这会产生相同的问题(谷歌上述错误)。
题
无论如何,有没有在类方面解决此问题,因此API用户感觉不到这一点,并且在编译时检测到错误?
也就是说,添加重载
void operator[](size_t t) {
throw std::runtime_error("don't");
}
Run Code Online (Sandbox Code Playgroud)
不是一个好的解决方案。
Sto*_*ica 148
之所以std::string(0)有效,是因为它0是一个空指针常量。所以0匹配带指针的字符串构造函数。然后,代码将违反不能将null指针传递给的先决条件std::string。
0如果它是运行时的值,则只有文字会被解释为空指针常量,int因为您不会遇到这个问题(因为过载解析会寻找int转换)。文字也不是1问题,因为1它不是空指针常量。
由于这是一个编译时问题(字面无效值),因此您可以在编译时捕获它。添加此形式的重载:
void operator[](std::nullptr_t) = delete;
Run Code Online (Sandbox Code Playgroud)
std::nullptr_t是的类型nullptr。它会匹配任何空指针常量,无论是0,0ULL或nullptr。并且由于删除了该函数,因此在重载解析期间将导致编译时错误。
Pet*_*ter 23
一种选择是声明它的private重载operator[]()接受一个整数参数,而不定义它。
该选项可与所有C ++标准(1998年以后)一起使用,与void operator[](std::nullptr_t) = delete从C ++ 11开始有效的选项不同。
使其operator[]()成为private成员将导致示例上的可诊断错误 ohNo[0],除非该表达式由成员函数或friend该类使用。
如果从成员函数或friend类的成员使用该表达式,则将编译代码,但是-由于未定义函数-通常,构建会失败(例如,由于函数未定义而导致的链接器错误)。
| 归档时间: |
|
| 查看次数: |
3816 次 |
| 最近记录: |