Confirmed users
1,345
edits
Nnethercote (talk | contribs) No edit summary |
Nnethercote (talk | contribs) |
||
| Line 111: | Line 111: | ||
=== An Example Involving Inheritance === | === An Example Involving Inheritance === | ||
foo | Things are a little trickier when inheritance is involved. Every sub-class needs to have its own implementation of <tt>SizeOfExcludingThis</tt>. | ||
class B { | |||
virtual foo() { ... } | |||
virtual NS_MUST_OVERRIDE size_t | |||
SizeOfExcludingThis(nsMallocSizeOfFun aMallocSizeOf) const | |||
{ | |||
... | |||
} | |||
}; | |||
class D : public B { | |||
virtual foo() { ... } | |||
virtual NS_MUST_OVERRIDE size_t | |||
SizeOfExcludingThis(nsMallocSizeOfFun aMallocSizeOf) const MOZ_OVERRIDE | |||
{ | |||
size_t n = B::SizeOfExcludingThis(aMallocSizeOf); | |||
n += ... // measure D-specific fields | |||
} | |||
}; | |||
Things to note: | |||
* <tt>D::SizeOfExcludingThis</tt> must override <tt>B::SizeOfExcludingThis</tt>. If it doesn't, if we have a <tt>B*</tt> pointer that actually points to a <tt>D</tt> object, we'll end up calling <tt>B::SizeOfExcludingThis</tt> instead of <tt>D::SizeOfExcludingThis</tt>, and thus we'll fail to measure any objects that <tt>D</tt>'s fields point to. | |||
* <tt>D::SizeOfExcludingThis</tt> must also call <tt>B::SizeOfExcludingThis</tt>, to ensure that any objects pointed to by fields inherited from <tt>B</tt> are measured. | |||
* The <tt>NS_MUST_OVERRIDE</tt> is an annotation that indicates that this function must be overridden by any sub-classes. It's used by some static analysis tools. Currently these tools aren't running, but they might in the future, and it's a useful piece of documentation. | |||
* The <tt>MOZ_OVERRIDE</tt> annotation says that <tt>D::SizeOfExcludingThis</tt> overrides the corresponding function in <tt>B</tt>. On supporting compilers it gets expanded to the <tt>override</tt> keyword. It's useful to avoid accidentally having small mismatches in the function signatures that prevent the overriding from happening. | |||
* The definitions of <tt>SizeOfIncludingThis</tt>, if needed, are straightforward and like the ones above. | |||
=== Other Considerations === | === Other Considerations === | ||