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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!