| Home | Libraries | People | FAQ | More

## Containers and move semantics

Movable but non-copyable types can be safely inserted into containers and movable and copyable types are more efficiently handled if those containers internally use move semantics instead of copy semantics. If the container needs to "change the location" of an element internally (e.g. vector reallocation) it will move the element instead of copying it. Boost.Container containers are move-aware so you can write the following:

    #include <boost/container/vector.hpp>
    #include <cassert>

    //Remember: 'file_descriptor' is NOT copyable, but it
    //can be returned from functions thanks to move semantics
    file_descriptor create_file_descriptor(const char *filename)
    {  return file_descriptor(filename);  }

    int main()
    {
       //Open a file obtaining its descriptor, the temporary
       //returned from 'create_file_descriptor' is moved to 'fd'.
       file_descriptor fd = create_file_descriptor("filename");
       assert(!fd.empty());

       //Now move fd into a vector
       boost::container::vector<file_descriptor> v;
       v.push_back(boost::move(fd));

       //Check ownership has been transferred
       assert(fd.empty());
       assert(!v[0].empty());

       //Compilation error if uncommented since file_descriptor is not copyable
       //and vector copy construction requires value_type's copy constructor:
       //boost::container::vector<file_descriptor> v2(v);
       return 0;
    }