LearnFrenzy
Sign in Take a free test

Constructors and Destructors · Predict the Output · Question 17

How vector reallocation moves elements Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 17 Back to Exercise

What is the output of the following C++ program?

main.cpp
#include <iostream>
#include <vector>

struct Item {
    static inline int copies = 0, moves = 0;
    Item() = default;
    Item(const Item&) { ++copies; }
    Item(Item&&) noexcept { ++moves; }
};

int main() {
    std::vector<Item> v;
    v.reserve(2);
    v.emplace_back();
    v.emplace_back();
    v.emplace_back();      // capacity 2 is exceeded: the vector must reallocate
    std::cout << Item::copies << ' ' << Item::moves << ' ' << v.size() << '\n';
    return 0;
}
  • A 0 2 3 Correct
  • B 2 0 3
  • C 0 0 3
  • D 0 3 3
Correct Answer: Option A

The third element does not fit, so the vector allocates a new buffer and transfers the two existing elements. Because the move constructor is noexcept, it moves them (2 moves, 0 copies). Without noexcept it would copy.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links