gpt4 book ai didi

c++ - 模式名称/写得好吗?

转载 作者:行者123 更新时间:2023-11-30 05:16:46 25 4
gpt4 key购买 nike

我有以下代码:

文档头文件

class CMyDoc
{
public:
class Suspender
{
friend class CMyDoc;

static bool m_suspending;
inline static const bool IsSuspending() { return m_suspending; }

public:
Suspender()
{
m_suspending = true;
}

~Suspender()
{
m_suspending = false;
}
};
}

文档源文件

静态变量初始化:

bool CMyDoc::Suspender::m_suspending = false;

检查是否处于“不允许”做事状态,如果是,则不要做:

void CMyDoc::SomeMethod()
{
if (!Suspender::IsSuspending())
DoThings();
}

我想在“不允许”状态下运行一些代码的地方

声明一个 Suspender 类型的变量。自动会在报关单上加上“不允许状态”。但最大的好处是,当堆栈帧结束时,它会返回到“允许”状态,因为它传递了 s 变量的析构函数。

void CMyView::DoSomething()
{
CMyDoc::Suspender s;
((CMyDoc*) GetDocument())->SomeMethod();
}

问题:

  1. 模式的名称是什么?
  2. 我这样做的方式是否最正确?我可以避免使用静态变量吗?

最佳答案

不,我认为您没有以最正确的方式进行操作,而且由于其中的缺陷,我也不认为它是真正的 RAII。

我认为可以在没有线程的情况下证明存在的缺陷。

void SomeViewMethod()
{
Suspender s1;
((CMyDoc*) GetDocument())->SomeMethod();
}

SomeOtherViewMethod()
{
Suspender s2;
((CMyDoc*) GetDocument())->SomeMethod();

SomeViewMethod();

// this looks like suspender s2 should be suspending the next call...
// but when the s1 inside SomeViewMethod went out of scope it turned off suspending
((CMyDoc*) GetDocument())->SomeMethod();
}

可以通过将 bool 替换为 int 以允许嵌套暂停来解决此特定问题。 int 将由每个悬挂器递增,如果值 = 0,则悬挂将关闭。

(以前我用这样的模式成功控制过重复重绘)

关于c++ - 模式名称/写得好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42485868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com