ProgrammingVery hardProduct-company placement · C++

What is printed?

What is printed?
struct A {
    A()                  { cout << "D"; }
    A(const A&)          { cout << "C"; }
    A(A&&) noexcept      { cout << "M"; }
};
int main() {
    vector<A> v;
    v.reserve(2);
    A a;
    v.push_back(a);
    v.push_back(std::move(a));
}
  1. A. DCC
  2. B. DMM
  3. C. DCM
  4. D. DDCM

Correct answer: C. DCM

reserve allocates capacity without constructing elements. push_back of an lvalue copy-constructs the element; push_back of std::move(a) picks the rvalue overload and move-constructs. No reallocation happens within the reserved capacity.

More OOP with C++ and Java questions

Exams that ask this topic