Question 20
Back to Exercise
What is the output of the following C++ program?
#include <iostream>
#include <memory>
struct Live {
static inline int n = 0;
Live() { ++n; }
Live(const Live&) { ++n; }
~Live() { --n; }
};
int main() {
Live a;
Live b = a;
auto p = std::make_unique<Live>();
std::cout << Live::n << ' ';
{
Live c, d;
std::cout << Live::n << ' ';
}
p.reset();
std::cout << Live::n << '\n';
return 0;
}
- A 3 5 2 Correct
- B 2 4 2
- C 3 5 3
- D 3 3 2
Correct Answer: Option A
a, its copy b, and the heap object make 3; c and d raise it to 5 inside the block; after the block and p.reset() only a and b remain. The copy constructor must also increment, or the count would drift.
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!