Question 17
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <memory>
struct Task {
int id;
explicit Task(int i) : id(i) {}
~Task() { std::cout << "~Task" << id << ' '; }
};
void run(std::unique_ptr<Task> t) { std::cout << "run" << t->id << ' '; } // t dies here
void peek(const Task& t) { std::cout << "peek" << t.id << ' '; }
int main() {
auto a = std::make_unique<Task>(1);
auto b = std::make_unique<Task>(2);
peek(*a);
run(std::move(a));
std::cout << (a ? "a" : "-") << ' ';
peek(*b);
std::cout << "end ";
return 0;
}
- A peek1 run1 ~Task1 - peek2 end ~Task2 Correct
- B peek1 run1 - peek2 end ~Task1 ~Task2
- C peek1 run1 ~Task1 a peek2 end ~Task2
- D peek1 run1 - peek2 end ~Task2 ~Task1
Correct Answer: Option A
peek borrows the object through a reference. run takes ownership by value, so Task 1 is destroyed when run returns and a is left empty. Task 2 is destroyed when main ends.
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!