Does std::vector "move" implicitly?

421 views Asked by At

Consider the following code:

#include <iostream>
#include<vector>
#include<unordered_map>
class Domain {
    public:    
        enum class fieldname {
            pos_x, pos_y
        };
        std::unordered_map<fieldname, std::vector<double>> data;
};
int main()
{
    Domain d;
    std::vector<double> f = {1, 3, 4, 5};
    d.data[Domain::fieldname::pos_x] = f;  
    // if f is large? 
    // d.data[Domain::fieldname::pos_x] = std::move(f);   
    // use d for other stuff 
    // ...
    return 0;
}

I have assigned f to the map member using a copy. I would like to find out if using std::move like in the commented line below it will be different in terms of a) memory usage b) runtime when f is a large vector (say 10% RAM). Thank you.

1

There are 1 answers

0
Guillaume Racicot On

First, let's address the "implicit move" thing.

In this case, f is an lvalue. It cannot be bound to rvalue reference. This means the std::vector type cannot use the move constructor and will fall back to the copy constructor.

On the other hand, this code will move:

int main()
{
    Domain d;
    d.data[Domain::fieldname::pos_x] = std::vector<double>{1, 3, 4, 5};  
    return 0;
}

In this case, the entity std::vector<double>{1, 3, 4, 5} is a prvalue and will be moved from.

If the vector is really large and new memory cannot be allocated, you'll get a std::bad_alloc exception, not a move.


Now for the resource use difference.

When you copy a vector, a second memory allocation will be requested to the memory allocator. Even if the original vector is deallocated briefly after, you had a moment in time where you needed twice the amount of memory to copy the vector.

As for the speed, generally we can assume memory allocations and copying is slower, but you can't be really sure as there is always special cases and details that weren't thought of. If there is a need for performance, you must measure the code, and optimize it to fit the performance needs. Without measurements, your changes could makes it slower without you knowing it.