i was tying to understand the flyWeight design pattern using the following example : full source code : https://refactoring.guru/design-patterns/flyweight/cpp/example
class Flyweight
{
private:
SharedState *shared_state_;
public:
Flyweight(const SharedState *shared_state) : shared_state_(new SharedState(*shared_state))
{
}
Flyweight(const Flyweight &other) : shared_state_(new SharedState(*other.shared_state_))
{
}
~Flyweight()
{
delete shared_state_;
}
...
}
};
class FlyweightFactory
{
private:
std::unordered_map<std::string, Flyweight> flyweights_;
/**
* Returns a Flyweight's string hash for a given state.
*/
std::string GetKey(const SharedState &ss) const
{
return ss.brand_ + "_" + ss.model_ + "_" + ss.color_;
}
public:
FlyweightFactory(std::initializer_list<SharedState> share_states)
{
for (const SharedState &ss : share_states)
{
this->flyweights_.insert(std::make_pair<std::string, Flyweight>(this->GetKey(ss), Flyweight(&ss)));
}
}
...
}
when populating the Hash map in the constructor of FlyWeightFactory class , the value of the first element was created by the constructor FlyWeight(SharedState* ss) but the second element's value was created by the copy constructor if the copy constructor of FlyWeight is not implemented , an exception will be raised :read access violation can anyone please explain this than you