dgel
dgel

Reputation: 164

Why can't I emplace ifstreams in a vector?

The following example program doesn't compile for me on either clang 3.1 or gcc 4.8:

#include <fstream>
#include <vector>

using namespace std;

int main()
{
    vector<ifstream> bla;
    bla.emplace_back("filename");
    return 0;
}

However, I thought emplace_back should

"Insert a new element at the end of the vector, right after its current last element. This new element is constructed in place using args as the arguments for its construction."

Does anyone know why this doesn't compile then? did I misunderstand or are the library implementations not yet complete?

Upvotes: 15

Views: 972

Answers (3)

Autolykos
Autolykos

Reputation: 203

Since it isn't fixed yet (AFAIK), here's a quick workaround:

typedef std::shared_ptr<std::ifstream> SharedIFS;
inline SharedIFS MakeIFS(const std::string &file) {
    return SharedIFS(new std::ifstream(file));}

Unless I missed something stupid, the SharedIFS should be moveable and copyable just fine. It has some overhead compared to plain emplace_back, but at least you can put it into a vector.

Upvotes: 0

Arne Kjetil Andersen
Arne Kjetil Andersen

Reputation: 483

Streams in c++11 are movable, so in theory you should be able to do what you want, problem is that movable streams have not yet been implemented in gcc/libstdc++.

To back up my answer further please take a look at gcc/libstdc++ c++11 status: http://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2011

Especially 27.5, 27.8, 27.9

Upvotes: 15

Mike Seymour
Mike Seymour

Reputation: 254721

That's a bug in the implementation of std::basic_istream. It should be movable, but isn't; and only movable types can be stored in a vector.

Here is the bug report against GCC.

Upvotes: 7

Related Questions