LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 13

A weak_ptr cache that reloads expired entries Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 13 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <map>
#include <memory>
#include <string>

std::map<std::string, std::weak_ptr<std::string>> cache;
int loads = 0;

std::shared_ptr<std::string> get(const std::string& key) {
    if (auto p = cache[key].lock()) return p;
    ++loads;
    auto p = std::make_shared<std::string>("data:" + key);
    cache[key] = p;
    return p;
}

int main() {
    auto a = get("home");
    auto b = get("home");          // still alive: no reload
    a.reset(); b.reset();          // nobody uses it any more
    auto c = get("home");          // expired: reload
    auto d = get("about");
    std::cout << loads << ' ' << *c << ' ' << cache.size() << '\n';
    return 0;
}
  • A 3 data:home 2 Correct
  • B 2 data:home 2
  • C 4 data:home 2
  • D 3 data:home 3
Correct Answer: Option A

The cache holds weak_ptrs, so it never keeps entries alive by itself. home is loaded, reused, freed, then loaded again; about is loaded 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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links