Question 20
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <memory>
int main() {
int freed = 0;
auto deleter = [&freed](int* p) { std::cout << "free " << *p << ' '; ++freed; delete p; };
{
std::unique_ptr<int, decltype(deleter)> a(new int(1), deleter);
std::shared_ptr<int> b(new int(2), deleter);
auto c = b;
std::cout << "| ";
}
std::cout << freed << '\n';
return 0;
}
- A | free 2 free 1 2 Correct
- B | free 1 free 2 2
- C | free 2 free 2 free 1 3
- D free 1 free 2 | 2
Correct Answer: Option A
Locals are destroyed in reverse order: c (count drops to 1), b (count 0: its deleter frees 2), then a frees 1. Each object is deleted exactly once.
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!