rmaicle

Programming is an endless loop; it's either you break or exit.

Licensed under a Creative Commons Attribution-ShareAlike 4.0 International License (CC BY-SA).
You are free to copy, reproduce, distribute, display, and make adaptations but you must provide proper attribution. Visit https://creativecommons.org/ or send an email to info@creativecommons.org for more information about the License.

Call State Checker

Date: 2016-02-21 21:02:13 +0000

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.

  •  class
  •  destructor