我想做这样的事情:
std::wistream input = std::wifstream(text);
if (!input) input = std::wistringstream(text);
// read from input
即。将文本解释为文件名,或者,如果不存在此类文件,则使用其内容而不是文件的内容。
我当然可以使用std::wistream * input
,然后使用new
和delete
来获取实际流。但是,我必须将所有这些封装在一个类中(构造函数和析构函数,即用于异常安全的正确RAII)。
还有另一种方法可以在堆栈上执行此操作吗?
答案 0 :(得分:2)
您可以将使用std::wistream& input
的逻辑抽象为自己的函数,然后使用std::wifstream
或std::wistringstream
作为适当的调用。
答案 1 :(得分:2)
我当然可以使用std :: wistream *输入,然后使用new和delete实际流。但是,我必须将所有这些封装在一个类中(构造函数和析构函数,即用于异常安全的正确RAII)。
这是std::unique_ptr
的用途。只需使用std::unique_ptr<std::istream>
。
答案 2 :(得分:1)
答案 3 :(得分:1)
您是否考虑过auto_ptr或unique_ptr来管理wistream指针?