Call State Checker
I came across a situation where I needed to test whether a member function was called.
I used a flag which is initially unset which a concerned function sets. The test program must then have access to that flag to verify the state.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Flag {
private:
bool state { false };
public:
void set() { state = true; }
bool is_set() const { return state; }
};
class CallFlag {
private:
Flag *flag { nullptr };
public:
void set_ref(Flag *f) { flag = f; }
void set() {
if (flag) {
flag->set();
}
}
};
The Flag
class holds the actual state, initially set to false
, meaning our destructor is not yet called.
The CallFlag
class is a convenience class.
The following code shows how it was used.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
struct A {
CallFlag dtorFlag;
~A() { dtorFlag.set(); }
};
int main()
{
Flag flag;
{
A a;
a.dtorFlag.set_ref(&flag);
std::cout << std::boolalpha << flag.is_set() << std::endl; // false
}
std::cout << std::boolalpha << flag.is_set() << std::endl; // true
}
Using Boost
The above solution can be simplified using boost::logic::tribool
.
Which means the Flag
class is no longer necessary.