c++ - 使用运算符重载 c++ 进行监控

标签 c++ operator-overloading

我想编写一个所有运算符都重载的包装类,这样我就可以检测到我们何时写入/读取或修改其内容。例如:

probe<int> x;
x = 5;     // write
if(x) {    // read
   x += 7; // modify
}

有人做过吗?如果不是,我必须重载哪些运算符以确保我不会错过任何东西?

最佳答案

将此作为一个共同的想法。 有很多像 and= |= [] 这样的运算符在你的情况下可能不是主要的。

template < typename T >
struct monitor
{
    monitor( const T& data ):
        data_( data )
    {
        id_ = get_next_monitor_id(); 
    }

    monitor( const monitor& m )
    {
       id_ = get_next_monitor_id();

       m.notify_read();
       notify_write();

       data_ = m.data_;
    }

    operator T()
    {
        notify_read();
        return data_;    
    }

    monitor& operator = ( const monitor& m )
    {
        m.notify_read();
        notify_write();

        data_ = m.data_;
        return *this;
    }

    monitor& operator += ( const monitor& m )
    {
        m.notify_read();
        notify_write();

        data_ += m.data_;
        return *this;
    }
/*
    operator *=
    operator /=
    operator ++ ();
    operator ++ (int);
    operator -- ();
    operator -- (int);
*/
private:
    int id_;
    T data_;

    void notify_read()
    {
        std::cout << "object " << id_ << " was read" << std::endl;
    }

    void notify_write()
    {
        std::cout << "object " << id_ << " was written" << std::endl;
    }
};

关于c++ - 使用运算符重载 c++ 进行监控,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/606135/

相关文章:

F#运算符(operator)重载: (+) for a user defind type

c++ - 重载运算符 << undefined reference

c++ - 在不包含在另一个范围内的范围内找到第一个元素

c++ - Boost 安装失败 : The system cannot find the path specified

c++ - 如何从 C++ 中的文件中随机获取信息?

python - Python 3.x 中的 `__rdiv__()` 和 `__idiv__` 运算符是否已更改?

c++ - 这些在 `this` 上调用运算符的不同方式有什么区别?

c++ - 重载运算符<<时出错, "cannot overload functions distinguished by return type alone"

c++ - 在 Cocoa 应用程序中使用大型 C++ 库的推荐方法?

c++ - 如何为四叉树批量插入的坐标实现 z 顺序排序 - C++