Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I emplace ifstreams in a vector?

Tags:

c++

c++11

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?

like image 644
dgel Avatar asked Jun 13 '13 14:06

dgel


People also ask

What is emplace in vector?

The vector::emplace() is an STL in C++ which extends the container by inserting a new element at the position. Reallocation happens only if there is a need for more space. Here the container size increases by one.

How does vector emplace work?

emplace_back(): This method is used instead of creating the object using parameterized constructor and allocating it into a different memory, then passing it to the copy constructor, which will insert it into the vector. This function can directly insert the object without calling the copy constructor.


Video Answer


2 Answers

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

like image 80
Arne Kjetil Andersen Avatar answered Oct 06 '22 17:10

Arne Kjetil Andersen


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.

like image 40
Mike Seymour Avatar answered Oct 06 '22 17:10

Mike Seymour