简体   繁体   中英

How do I do a check before every read and write of a variable, c++, access control

I am trying to do a check whenever a value is written or read to while in debug mode, to cache data races and other threadding errors before shipping. This system is only intended for debug mode and should only work as a info gathering system, so no overhead in shipping builds.

Sudo code:

template<T>
struct Resource
{
    /*
    Here I need to somehow do a check on all reads and writes?
    How would this class look if it just where to print "read" and "write",
    on their corresponding actions, and is this even possible?

    Edit: The resource class works like wrapper of another type,
    this means the it should also function as so. This can be achieved
    by overriding the &operator.

    Maybe there is something else that can be overwritten in order
    to intercept writes?
    */

    explicit operator T&() { return resource; }
}

class SomeType()
{
public:
    uint32_t GetSomething();
    uint32_t somethingElse;
}

Resource<SomeType> resource1;
Resource<SomeType> resource2;
Resource<SomeType> resource3;

AccessPolicy accessPolicy;
accessPolicy.AddResource(resource1, EAccessPolicy::Read);
accessPolicy.AddResource(resource2, EAccessPolicy::Write);

Task task = Task(&ExampleTask, accessPolicy);

static void ExampleTask()
{
    auto something = resource1.GetSomething(); // Allowed

    resource2 = SomeClass(); // Allowed
    resource2.somethingElse = 4;

    resource3.GetSomething(); // Unauthorized access assert
}

Do you mean something like this?

template<T>
struct Resource
{
    Resource(const T &value) { v = value; }
    T & GetSomething(Task & task) {
        if (task.is_allowed(EAccessPolicy::Read, this)) {
            std::cout << "read" << std::endl;
            return v;
        } else {
            // error
        }
    }
    void SetSomething(Task & task, const T & t) {
        if (task.is_allowed(EAccessPolicy::Write, this)) {
            std::cout << "write" << std::endl;
            v = t;
        } else {
            // error
        }
    }
private:
    T v;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM