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?

Morwenn
  • 21,684
  • 12
  • 93
  • 152
Łukasz Lew
  • 48,526
  • 41
  • 139
  • 208

1 Answers1

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

RiaD
  • 46,822
  • 11
  • 79
  • 123
  • 1
    In order to meet the strong exception safety requirements, using `std::move_if_noexcept` is more likely. This requires a noexcept move constructor unless the copy constructor is inaccessible, deleted, or otherwise unavailable. – Howard Hinnant Jun 10 '13 at 15:10
  • If I remember right `vector` and the other standard containers actually use `move_if_noexcept` which is the same as a move if the move constructor is `noexcept` or a normal copy otherwise. – John5342 Jun 10 '13 at 15:14
  • Darn. Beaten to the punch :-P – John5342 Jun 10 '13 at 15:15