LearnFrenzy
Sign in Take a free test

Static and Friend Members · Static and Friend Programs · Question 9

Static factory with a cache (flyweight) in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Write a Color class with a private constructor and a static get(name) that returns a shared object, creating each color only once and caching it in a static map; count how many objects were really created.

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

class Color {
    std::string name_;
    static inline int created_ = 0;
    explicit Color(std::string n) : name_(std::move(n)) { ++created_; }
public:
    static std::shared_ptr<const Color> get(const std::string& name) {
        static std::map<std::string, std::shared_ptr<const Color>> cache;
        auto& slot = cache[name];
        if (!slot) slot = std::shared_ptr<const Color>(new Color(name));   // private ctor: make_shared cannot call it
        return slot;
    }
    static int created() { return created_; }
    const std::string& name() const { return name_; }
};

int main() {
    auto a = Color::get("red");
    auto b = Color::get("blue");
    auto c = Color::get("red");
    for (const char* n : {"red", "green", "blue", "green"}) Color::get(n);
    std::cout << a->name() << ' ' << (a == c) << ' ' << (a == b) << ' ' << Color::created() << '\n';
    return 0;
}

Output Verified by compiling and running

red 1 0 3

Requesting the same name returns the same shared object, so only three Color objects ever exist (red, blue, green). Because the constructor is private, the static member function creates them with new inside a shared_ptr.

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