1

I have a class A that owns an object of type class B. B should be lazily instantiated (this is a requirement), and it is used by some of A's methods.

currently it is implemented by calling allocate_b() at the beginning of every one of A's methods that needs to use B. allocate_b() will create a new instance of B if one is not already created. example:

class B {
   ...
};


class A {
private:
    B* _b_object;
    B* allocate_b() {/*allocate _b_object if NULL*/}

public:
    void foo() 
    {
        allocate_b();
        _b_object->do_something();
    }
};

you can see that this code is bug prone, and can (and did) cause problems if someone forgets to add allocate_b when implementing a new method.

I want to replace the pointer to B with a wrapper class that overrides operator-> to perform the allocation for the first time if necessary. I prefer to use an existing code and not write it myself, and I wonder if anyone knows of something that does it already.

also I would be happy to hear of other ideas to solve the problem

Thank you.

danny
  • 319
  • 3
  • 9
  • If you're asking for an existing library or such, then this is a question asking us to recommend or find a book, tool, software library, tutorial or other off-site resource, which is off-topic for SO. If you try to create a wrapper yourself, and wants help with some problem with your attempt, then it's on-topic. Please be careful how you phrase your question. – Some programmer dude Jun 25 '15 at 13:16

0 Answers0