Łukasz Lew
Łukasz Lew

Reputation: 50278

Will a vector of movable elements resize efficiently?

Let's assume T is moveable object:

vector<T> v;
v.resize(...) 

if reallocation is needed, then will that code invoke copy, or move constructor on all elements?

If the answer is "move constructor" then how does the compiler know that it should use this one?

Upvotes: 4

Views: 314

Answers (1)

RiaD
RiaD

Reputation: 47620

#include <vector>
#include<memory>

int main() {

    std::vector<std::unique_ptr<int>> v;

    for(int i = 0; i < 1000; ++i) {
        v.push_back(std::unique_ptr<int>(new int));
    }
}

http://ideone.com/dyF6JI

This code would not be compiled if std::vector used copy constructor.

If the answer is "move constructor" then how does the compiler know that it should use this one?

std::vector could use std::move

If it use std::move but there's no move constructor, it will be equivalent to just using copy constructor

Upvotes: 6

Related Questions