似乎无法使用C++中的临时值构造将istream的非const引用构造函数。构造函数中的临时非const istream引用(C++)
#include <iostream>
#include <sstream>
using namespace std;
class Bar
{
public:
explicit Bar(std::istream& is) {}
};
int main()
{
istringstream stream1("bar1");
Bar bar1(stream1); // OK on all platforms
// compile error on linux, Mac gcc; OK on Windows MSVC
Bar bar2(istringstream("bar2"));
return 0;
}
这个编译罚款与MSVC,但不是与gcc。使用gcc我得到一个编译错误:
g++ test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:18: error: no matching function for call to ‘Bar::Bar(std::istringstream)’
test.cpp:9: note: candidates are: Bar::Bar(std::istream&)
test.cpp:7: note: Bar::Bar(const Bar&)
有什么哲学上错构建Bar对象的第二路(BAR2)?它对我来说看起来更好,并且不需要只是暂时需要的stream1变量。
编辑:为了回应Johannes Schaub的评论,我想给出更多的上下文。首先,这不是我第一次被C++的这种行为所困扰,所以我真的对这个问题的更高层次的哲学讨论感兴趣。也就是说,在这种特殊情况下,我有一个读入包含用于构造对象的数据的文件的类。我也喜欢编写使用字符串而不是文件的自动化测试。但使用该文件进行构建是最主要的用例。所以我决定创建一个采用istream的构造函数,所以我可以使用文件(流)或字符串(流)。我就是这样来的。我的测试程序直接从字符串构造对象,以模拟读取文件。这为我节省了为每个小测试创建单独数据文件的麻烦。
您可以通过'istringstream(“bar2”)。seekg(0)'作为解决方法。 – 2010-03-09 00:44:32
MSVC行为是一个非标准的扩展,它会产生一个警告,我想如果你启用标准模式(/ Za),你也会得到一个错误。 – 2010-03-09 00:45:45
@Johannes Schaub:非常聪明。我想任何返回对临时对象的引用的方法都可以在这里使用。 – 2010-03-09 00:52:33