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

Clever way to clean dirty flag in c++

本文关键字:方法 标志 C++      更新时间:2023-10-16

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

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 方法是在派生类上实现的,我需要一种方法来强制执行在执行 Build 方法后将此标志设置为false的方法,而不仅仅是为编写派生类的人员留下一个准则,让他们在他们的"Build"方法中dirty = false

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

一种常见的方法是有一个垂直界面和一个水平界面(受保护和公共(。

"水平接口"是类的用户看到的接口,"垂直"接口是派生类实现者重写以添加功能的接口。

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
}
};