此代码片段(https://gcc.godbolt.org/z/hKDMxm):
#include <iostream>
#include <sstream>
using namespace std;
int main() {
auto s = (ostringstream{} << "string").str();
cout << s;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用 msvc 编译并按预期运行,但无法使用 clang 9.0.0 和 gcc 9.2 进行编译,并给出以下错误消息:no member named 'str' in 'std::basic_ostream<char>'。查看https://en.cppreference.com/w/cpp/io/basic_ostringstream/str显然str()有ostringstream. 为什么 clang 和 gcc 无法编译此代码?
显然有
str()成员ostringstream
是的,但是根据cppreference这个重载<<应该返回对basic_ostream<...>而不是的引用ostringstream。
libstdc++(GCC 的标准库)正是这样做的,而 libc++(Clang 的标准库)和 MSVC 的标准库在技术上在这里表现不正确。
但是,似乎有一个开放的缺陷报告表明<<与右值流一起工作的重载应该返回传递给它的确切流类型。如果它被接受,您的代码将有效。