如何返回一个fstream(C ++ 0x) [英] How to return an fstream (C++0x)

查看:106
本文介绍了如何返回一个fstream(C ++ 0x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我会直接进入它,并从代码开始:

I think I'll get right into it and start with the code:

#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";
}

基本上,我需要返回一个stream。当然,你不能复制一个stream,所以我在类测试中的代码,我得到了上面的编译和工作,你会期望(在gcc 4.5)。

Basically, I need to return an ofstream. Of course you can't copy an ofstream, so I fiddled around with the code in the class test, and I got the above to compile and work as you would expect (on gcc 4.5).

但是我有一个坏的感觉,这是因为我的编译器对auto os = test()做返回值优化(RTO)。事实上,如果修改为以下:

But I have a bad feeling this is just due to my compiler doing "Return Value Optimization" (RTO) on "auto os = test()". Indeed, if modify to the following:

int main()
{
    auto os = test("testfile");
    os << "Test1\n";
    auto os2 = std::move(os);
    os2 << "Test2\n";
}

我不再在输出中获得Test1和Test2。

I no longer get both Test1 and Test2 in the output.

事情是,类test是不可复制的,所以没有机会被重复。我只想要能够从一个函数返回它。我似乎能够用GCC做到这一点。

The thing is, the class "test" isn't copyable, so there's no chance of the ofstream being duplicated. I just want to be able to return it from a function. And I seem to be able to do that with GCC.

我不想将智能指针解析为分配给流的堆,或重新打开文件,因为它目前工作没有做那些事情。我只是有一种感觉,我在我的方法是一个非标准,所以一个标准的方式做我所描述的是伟大的。

I'd rather not have dereference smart pointers to a heap allocated ofstream, or reopen the file, as it currently works without doing those things. I just have a feeling I'm being a little "non-standard" in my approach, so a standard way of doing what I've described would be great.

推荐答案

我要在这里回答我自己的问题:

I'm going to answer my own question here:

GCC C ++ 0x库特性页面,看看项目27.9,其内容如下:

In the GCC C++0x Library Features page, have a look at item 27.9, which reads:

27.9 - 基于文件的流 - 部分 - 缺少移动和交换操作

27.9 - File-based streams - Partial - Missing move and swap operations

我遇到了gcc的问题。

I guess that's probably the issue I'm having with gcc.

这篇关于如何返回一个fstream(C ++ 0x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆