Medium
Flyweight glyph cache handing out mutable references
What does this program print?
main.cpp
class GlyphFlyweight {
public:
explicit GlyphFlyweight(char c) : ch_(c) {}
char ch_; // intended to be shared, immutable "intrinsic" state
void render(int x) const { std::cout << ch_ << "@" << x << " "; }
};
class GlyphFactory {
public:
GlyphFlyweight& get(char c) {
auto it = cache_.find(c);
if (it != cache_.end()) return *it->second;
auto [inserted, _] = cache_.emplace(c, std::make_unique<GlyphFlyweight>(c));
return *inserted->second;
}
private:
std::unordered_map<char, std::unique_ptr<GlyphFlyweight>> cache_;
};
int main() {
GlyphFactory factory;
GlyphFlyweight& a1 = factory.get('a');
GlyphFlyweight& a2 = factory.get('a'); // same shared flyweight as a1
a1.render(0);
a2.ch_ = 'X'; // caller mutates what it thinks is "its own" glyph
a1.render(10); // uses the SAME underlying flyweight as a2
std::cout << "\n";
}18 of 44 in Design Patterns