Will returning an object call it's destructor?
I have a very simple class which handles callbacks. A caller asks for a
Callback from a Manager. So long as the Callback object is held by the
caller, it remains valid. Once the object dies however, it's destructor
sets a pointer inside the Manager to NULL so it knows to throw it away
when it next encounters it.
... or at least, that's the basic idea I'm after.
class Manager{
public:
void executeOnList() { ... }
Callback requestCallback(Drawable * target){
Drawable ** ptr = list.add(target);
return Callback(ptr); // <-- the point of interest
}
private:
List list;
};
class Callback{
friend Manager;
private:
Callback(Drawable ** targetPtr){
drawablePtr = targetPtr;
}
public:
~Callback(){
(*drawablePtr) = NULL; // <-- dtor of interest
}
private:
Drawable ** drawablePtr;
};
My question is, will that Manager::requestCallback() call the destructor
of Callback before returning the structure to it's caller?
If that is the case, would there be any way to prevent this, while (more
or less) maintaining the basic idea behind Callback's functionality?
Edit:
I've been thinking about it, and if the destructor is called when the
Callback exits requestCallback()'s scope, does that mean there would be a
matching constructor call in the Caller? If that's the case, could
something like this work?
class Callback{
friend Manager;
private:
Callback(int * _referenceCount){ // the referenceCount always starts at 0
referenceCount = _referenceCount;
++(*referenceCount);
}
public:
~Callback(){
--(*referenceCount);
}
private:
// if this value is 0 when it's encountered, the Callback is removed
int * referenceCount; // integer resides in Manager
};
No comments:
Post a Comment