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));
}- A. DCC
- B. DMM
- C. DCM
- 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
- What is printed? cpp int main() { uniqueptr<int> p = makeunique<int>(7); uniqueptr<int> q = std::move(p); cout << (p == nullptr) << q; }
- What is printed? cpp int main() { auto a = makeshared<int>(5); auto b = a; { auto c = a; cout << a.usecount(); } cout << a.usecount()…
- What is printed? cpp int main() { weakptr<int> w; { auto s = makeshared<int>(1); w = s; cout << w.expired(); } cout << w.expired(); }
- What is printed? cpp struct P { int a, b; P() : P(1) { cout << "x"; } P(int a) : P(a, 2) { cout << "y"; } P(int a, int b) : a(a), b(b) {…
- Which lines fail to compile? cpp struct F { explicit operator bool() const { return true; } }; int main() { F f; if (f) cout << "Y"; // L1…
- What is printed? cpp struct M { operator int() const { return 7; } }; int main() { M m; cout << m + 1; }