Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to return an fstream (C++0x)
    primarykey
    data
    text
    <p>I think I'll get right into it and start with the code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; class test : public std::ofstream { public: test(const std::string&amp; filename) { this-&gt;open(gen_filename(filename)); }; test(const test&amp;) = delete; //test(test&amp;&amp; old) = default; // Didn't compile test(test&amp;&amp; old) {}; private: std::string gen_filename(const std::string&amp; filename) { return filename + ".tmp"; } }; int main() { auto os = test("testfile"); os &lt;&lt; "Test1\n"; os &lt;&lt; "Test2\n"; } </code></pre> <p>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).</p> <p>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:</p> <pre><code>int main() { auto os = test("testfile"); os &lt;&lt; "Test1\n"; auto os2 = std::move(os); os2 &lt;&lt; "Test2\n"; } </code></pre> <p>I no longer get both Test1 and Test2 in the output.</p> <p>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.</p> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload