Hard
Flyweight factory backed by std::unordered_map
What happens when this program runs?
main.cpp
#include <iostream>
#include <string>
#include <unordered_map>
struct Glyph {
char symbol;
std::string font;
// imagine a large rasterized bitmap here
};
class GlyphFactory {
public:
const Glyph& get(char c) {
auto [it, inserted] = cache_.try_emplace(c, Glyph{c, "Inter"});
return it->second;
}
std::size_t buckets() const { return cache_.bucket_count(); }
private:
std::unordered_map<char, Glyph> cache_;
};
int main() {
GlyphFactory factory;
const Glyph& first = factory.get('A');
std::size_t before = factory.buckets();
for (char c = 'B'; c <= 'z'; ++c) factory.get(c); // grows the cache well past one bucket array
std::cout << (factory.buckets() > before) << " " << first.symbol << " " << first.font << "\n";
}43 of 44 in Design Patterns