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.