If by "default operator function" you mean you want the operator=()
to do everything that would be achieved if you simply did
Foo &operator=(const Foo &) = default;
but, in addition, increment a counter, then there is no direct way, since such an operator can only have one definition.
However, you can achieve a similar effect by using something like
class Counter
{
public:
Counter &operator=(const Counter &) {++counter; return *this;};
static int Count() {return counter;};
private:
static int counter;
};
and (in exactly one compilation unit that has visibility of the definition of class Counter
e.g. by including the header that contains the class definition) do
int Counter::counter = 0;
Then simply add a single Counter
as a private non-static member of your class Foo
. That way, every usage of a "defaulted" operator=()
in class Foo
will increment the Counter::counter
.
If your class Foo
is the only place that a Counter
is used, then the above will allow counting the number of times a Foo
is assigned. All you need to do to obtain the count, at any time, is call Counter::Count()
.
As noted by Caleth in comments, the class Counter
can be templated on the type, so a distinct counter for Foo
versus other classes can be established. This also opens the door for using CRTP (the Curiously Recurring Template Pattern) in which Foo
can derived from Counter<Foo>
to provide the desired capability.
There are some potential caveats to be aware of;
- The size of a
Counter
will be non-zero, so the size of a Foo
will probably change.
- You will need to ensure constructors and destructor of class
Counter
(however they are defined) work correctly with Foo
;
- The behaviour will be undefined if
Counter::count
ever overflows
(which caps the number of times your class can be assigned);
- There is nothing to stop other code from instantiating and assigning
a
Count
, which will mess up your count (although that possibility
might be mitigated (note I didn't say "countered") if Counter
has all members private
and specifies class Foo
as a friend
).