受我在上一个问题中观察的启发,我决定做一点测试:
#include <iostream>
#include <sstream>
int main()
{
char c = 'A';
std::stringstream ss("B");
// I know this is bad mojo; that's why I'm testing it
ss >> char(c);
std::cout << c << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
我的编译器版本:
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix
在C++ 03模式下编译clang,它编译并运行正常:
$ clang++ -Wall -pedantic -std=c++03 test.cpp
test.cpp:9:6: warning: expression result unused [-Wunused-value]
ss >> char(c);
~~ ^ ~~~~~~~
1 warning generated.
$ ./a.out
A
Run Code Online (Sandbox Code Playgroud)
它打印出来A,这很好,因为这个代码甚至不应该编译.切换到C++ 11模式,它在编译(error: invalid operands to binary expression ('std::stringstream' (aka 'basic_stringstream<char>') and 'int'))时正确错误.
是的,在C++ 03模式下它会发出警告,但它不是我期望的警告(我预期某种"通过引用临时"警告/错误,或者可能是警告/错误,表示不operator>>接受char参数).
我的问题是:为什么代码在C++ 03模式下成功编译?是否使用了一些替代的重载operator>>,避免通过引用临时?它是否过于宽松,让我暂时参考?我很困惑为什么clang完全接受这个代码; GCC 4.9在C++ 03/11模式中正确地出错,并且具有更多相关的错误(error: no match for 'operator>>' (operand types are 'std::stringstream {aka std::basic_stringstream<char>}' and 'char')).Clang在C++ 03模式下的行为令我感到困惑.
我认为它调用了operator bool()of std::stringstream,也就是说,代码被解释为
bool(ss) >> char(c);
Run Code Online (Sandbox Code Playgroud)
这当然是一个有效的陈述,没有任何效果。bool到return的隐式转换!fail()允许像这样的代码
while (ss >> foo)
...
Run Code Online (Sandbox Code Playgroud)
该标准允许转换为另一种类型,该类型转换为bool而不是普通类型bool(例如 a void*),以避免此类问题。显然你的实现没有利用这种自由。