0

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

  • For why it crashes see https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three. Please provide a [mre] – Alan Birtles May 31 '22 at 14:57
  • 1
    The `Flyweight` class has to manage dynamically allocated memory when copies are made. The compiler default version is not adequate, since it will simply make a shallow copy. Also, if you take a look at the duplicate link and go to the **Managing resources** section, the code there demonstrates you don't need all of the complexity you are showing us to duplicate the same issue. – PaulMcKenzie May 31 '22 at 15:02
  • You don't need `unordered_map` to duplicate the issue: `int main() { SharedState s("a", "b", "c"); Flyweight f(&s); Flyweight f2 = f; }` -- That will duplicate the error if the copy constructor for `Flyweight` is removed. – PaulMcKenzie May 31 '22 at 15:10
  • @PaulMcKenzie i fully understand the example in your last comment may question concerns this line this->flyweights_.insert(std::make_pair(this->GetKey(ss), Flyweight(&ss))); here from what i understand , we 're calling explicitly the constructor FlyWeight(SharedState* ss ). while debugging , for the first iteration the constructor FlyWeight(SharedState* ss ) was called , but for the rest of iteration the copy constructor was called that is my question – AbderrazekDev May 31 '22 at 16:57

0 Answers0