在 C++ 中清理脏标志的聪明方法

Clever way to clean dirty flag in c++

在这种情况下,我试图公开空间搜索结构的标准 API,其中用于构建结构的各种方法的输入数据是相同的,但搜索结构的方式是建造的是不同的。 我有基础 class 上的数据设置器和派生的 classes 需要实现的纯虚拟 Build() 方法来构建搜索结构。 下面是我的基地 class 的样子

class SpatialSearch
{
public:
  void SetData(Data data_)
  {
    this->data = data_;
    this->dirty = true;
  }

  virtual void Build() = 0;

  int search(Vec3 point)
  { 
    if(dirty)
      Build();
    // Code to perform a search. I won't get into the 
    // nitty gritty of this, but this exists as a commom
    // implementation on the base class for all the spatial 
    // search structures.
  }

private : 
  Data data;
  bool dirty;
}

因此,如果您注意到,每次搜索调用都会检查 dirty 标志。 如果数据在上次之后发生了变化,我会重建结构。 但是,Build 方法是在派生的 class 上实现的,我需要一种方法来强制执行 Build 方法后将此标志设置为 false 的方法,而不仅仅是为编写派生 class 的人在他们的 'Build' 方法中包含 dirty = false

简而言之,我需要一种方法来确保用户在每次执行 Build 方法后都设置了 dirty = false

一种常见的方法是使用垂直界面和水平界面(protected & public)。

"horizontal interface" 是 class 的用户看到的,"vertical" 是派生的 class 实现者覆盖以添加功能的。

class SpatialSearch
{
public:
  void SetData(Data data_)
  {
    this->data = data_;
    this->dirty = true;
  }

  void Build() // no longer virtual
  {
    internal_build(); 
    dirty = false;
  }

  int search(Vec3 point)
  { 
    if(dirty)
      internal_build();
    // Code to perform a search. I won't get into the 
    // nitty gritty of this, but this exists as a commom
    // implementation on the base class for all the spatial 
    // search structures.
  }

protected:
  virtual void internal_build() = 0; // implementers override this

private : 
  Data data;
  bool dirty;
}

class SpecialSpatialSearch
: public SpatialSearch
{
protected:
  void internal_build() override
  {
    // do the build without caring or knowing of the 
    // existence of the dirty flag
  }
};