LearnFrenzy
Sign in Take a free test

Move Semantics · Predict the Output · Question 16

Counting special member calls in a small program Answer, explanation & discussion

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

What is the output of the following C++ program on a 64-bit system?

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

struct T {
    static inline int c = 0, m = 0, d = 0;
    T() = default;
    T(const T&) { ++c; }
    T(T&&) noexcept { ++m; }
    ~T() { ++d; }
};

T make() { return T(); }

int main() {
    {
        std::vector<T> v;
        v.reserve(4);
        T a;
        v.push_back(a);            // copy
        v.push_back(std::move(a)); // move
        v.push_back(make());       // move from the temporary
        v.emplace_back();          // in place
    }
    std::cout << T::c << ' ' << T::m << ' ' << T::d << '\n';
    return 0;
}
  • A 1 2 6 Correct
  • B 1 2 4
  • C 2 2 6
  • D 1 3 6
Correct Answer: Option A

One copy, two moves. Destructors: the temporary from make(), the local a, and the four vector elements = 6.

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