避免指针比较的 C++ 技巧

标签 c++ pointers equality

我正在将代码库从一种编程风格转移到另一种编程风格。

我们有一个名为 Operand 的类型,定义如下:

class Operand
{...};

然后我们有

class OperandFactory
{
  public:
    const Operand *make_operand (...);
};

OperandFactory 用于散列Operand 并将其保存在表中。因此,如果您使用相同的参数调用 make_operand,您将获得相同的指针,并且对 Operand 的指针比较会激增。现在我需要添加一个功能,使它变得不可行。所以,我在 Operand 中实现了 operator== 并且如果我做了一个指针,我想以某种方式在编译时(更好)或运行时(总比没有好)生成错误Operand 的比较。实现这一目标的最佳方法是什么?

这只会在这个过渡阶段使用,所以我不介意这个解决方案是否看起来像 hack,只要它捕获代码库中的所有比较即可。

最佳答案

您可以重载运算符的地址以返回句柄并声明两个句柄的比较(无需定义)。这将导致链接器错误。

#include <iostream>

class Op;

class Handle {
    Op *pri_;
public:
    explicit Handle(Op *o) : pri_(o) {}
    Op *operator->() const { return pri_; }
    Op &operator*() const { return *pri_; }
};

 // force compile time errors on comparison operators
bool operator==(const Handle &, const Handle &) = delete;
bool operator!=(const Handle &, const Handle &) = delete;
bool operator>=(const Handle &, const Handle &) = delete;
bool operator<=(const Handle &, const Handle &) = delete;
bool operator<(const Handle &, const Handle &) = delete;
bool operator>(const Handle &, const Handle &) = delete;

class Op {
    int foo_;
public:
    explicit Op(int i) : foo_(i) { }
    Handle operator&() { return Handle(this); };
    void touch() const { std::cout << "foobar"; }
};


int main(int argc, char **argv) {
    Op i{10};
    Op j{20};

    auto c = &j; // works
    c->touch(); // works
    (*c).touch(); // works

    if (&j == &i) {
        /* will not compile */
    }

}

注意:

您必须满足 Handlerandom_access_iterator 要求!

Op i{10}
Handle ref = &i;

ref++; ref--; ++ref; --ref; ref = ref + 10; ref = ref - 10; // should all work.

关于避免指针比较的 C++ 技巧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25549422/

相关文章:

c - 指向char的指针数组和指向int的指针数组之间的区别

c - C 编程中哪个约定更好?

hashmap - 使用新的但相同值的键通过对象键访问 Haxe map

r - 比较 R 中的两个日期

C++循环继承依赖

c++ - 在 C++ 中创建头文件时出错

将 int 指针转换为 char 指针

c# - 为什么将 *nullable* 小数与 `0` 进行比较不同于将小数与 `0` 进行比较?

c++ - 将数组中的所有 float 元素添加到另一个数组中的每个 float 的优化方法

c++ - O(1) std 或 boost 列表连接