4

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?

4

1 回答 1

6
#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

于 2013-06-09T14:23:22.173 回答