Returning ifstream in a function

后端 未结 4 2150
日久生厌
日久生厌 2021-02-13 11:13

Here\'s probably a very noobish question for you: How (if at all possible) can I return an ifstream from a function?

Basically, I need to obtain the filename of a databa

4条回答
  •  感情败类
    2021-02-13 11:47

    No, not really. ifstream doesn't have a copy constructor, and if you try to return one, that means copying the instance in your function out to wherever the return needs to go.

    The usual workaround is to pass in a reference to one, and modify that reference in your function.

    Edit: while that will allow your code to work, it won't fix the basic problem. Right now, you're mixing two rather different responsibilities into a single function: 1) obtain a file name, 2) open or create that file. I think if you separate those, the code will be simpler, and make it much easier to eliminate the source of the problem you're seeing.

    Edit 2: Using a reference like this works perfectly well without an operator=. The general idea is something like:

    int open_file(char const *name, fstream &stream) { 
        stream.open(name);
    }
    

    The assignment operator is neither necessary nor useful in this case -- we simply use the existing fstream via the reference. An operator= would be necessary if and only if we had to pass the argument to the ctor. With a stream, we can default construct a stream that doesn't connect to a file, and then use open to connect to the file after the fact.

提交回复
热议问题