There is this code:
#include <iostream>
class CleverClass{
public:
CleverClass() : number(55){}
void cleverOperation(){
std::cout << number << std::endl;
}
private:
int number;
};
class NotCleverClass{
public:
NotCleverClass(CleverClass* cc) : cleverClass(cc){}
void callCleverOperation(){
// throw exception when cleverClass object doesn't exist anymore
cleverClass->cleverOperation();
}
private:
CleverClass* cleverClass;
};
NotCleverClass returnNCC(){
CleverClass CC;
NotCleverClass NCC(&CC);
NCC.callCleverOperation(); // prints 55
return NCC;
}
int main()
{
NotCleverClass returnedNCC = returnNCC();
returnedNCC.callCleverOperation(); // prints -858993460
return 0;
}
Object of class NotCleverClass is dependent to object of class CleverClass. When object of class CleverClass exists then object of class NotCleverClass can use its function cleverOperation() and everything works okey. However, when object of class CleverClass is going to lose existence, then calling its function may cause troubles.
One of the solutions is to keep in NotCleverClass weak pointer (boost::weak_ptr) of CleverClass object with reference checker, but there is still a problem when object of cleverClass is not going to be placed on free store (for example on stack). Are there some design patterns to monitor whether used object still exist and that calling its functions has any sense?
You can still use a
weak_ptreven if the object has automatic storage duration; you can give theshared_ptra custom deleter that does nothing; and make sure it is destroyed immediately before the object itself, by placing it in the same scope as the object. Something like this:This should work with either Boost or C++11 smart pointers. In C++11, you can replace the
null_deletefunctor with a lambda,[](void*){}.