我想直接开始编码:
#include <iostream>
#include <fstream>
#include <string>
class test : public std::ofstream
{
public:
test(const std::string& filename) { this->open(gen_filename(filename)); };
test(const test&) = delete;
//test(test&& old) = default; // Didn't compile
test(test&& old) {};
private:
std::string gen_filename(const std::string& filename)
{ return filename + ".tmp"; }
};
int main()
{
auto os = test("testfile");
os << "Test1\n";
os << "Test2\n";
}
基本上,我需要返回一个ofstream。当然,你不能复制一个ofstream,因此在类测试中,我围绕着代码进行了一些调整,并且我让以上的代码进行编译和工作,就像你期望的那样(在gcc 4.5上)。
但是我有一种不好的感觉,这只是因为我的编译器对“auto os = test()”执行了“返回值优化”(RTO)。实际上,如果修改为以下内容:
int main()
{
auto os = test("testfile");
os << "Test1\n";
auto os2 = std::move(os);
os2 << "Test2\n";
}
我在输出中不再同时获得Test1和Test2。
问题是,类“test”不可复制,因此没有复制ofstream的机会。我只想能够从函数中返回它。而且我似乎可以使用GCC做到这一点。
我不想使用智能指针解引用堆分配的ofstream或重新打开文件,因为目前在不进行这些操作的情况下就可以正常工作。我只是有点“非标准”地处理,所以能有一种标准方法来完成我所描述的内容就好了。