Question 7
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <memory>
#include <string>
#include <vector>
struct Song { std::string title; int plays = 0; };
int main() {
auto hit = std::make_shared<Song>(Song{"Kesariya"});
std::vector<std::shared_ptr<Song>> favourites{hit}, recent{hit, hit};
for (auto& s : recent) ++s->plays;
++favourites[0]->plays;
std::cout << hit->plays << ' ' << hit.use_count() << '\n';
recent.clear();
std::cout << hit.use_count() << '\n';
return 0;
}
- A 3 4 2 Correct
- B 1 4 2
- C 3 3 1
- D 3 4 4
Correct Answer: Option A
All four shared_ptrs point to the same Song, so every increment hits one object. Clearing recent drops two owners.
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!