图案的名称 /写得很好
Name of pattern / well written?
本文关键字:很好 更新时间:2023-10-16
我有以下代码:
DOC标头文件
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;
}
};
}
doc源文件
静态变量初始化:
bool CMyDoc::Suspender::m_suspending = false;
检查它是否在"不允许"执行状态上,如果是,请不要这样做:
void CMyDoc::SomeMethod()
{
if (!Suspender::IsSuspending())
DoThings();
}
我想在"不允许"状态
上运行一些代码声明Suspender
类型的变量。自动将在声明上放置"不允许的状态"。但是最大的好处是,当堆栈框架结束时,它将返回"允许"状态,因为它通过s
变量的破坏者。
void CMyView::DoSomething()
{
CMyDoc::Suspender s;
((CMyDoc*) GetDocument())->SomeMethod();
}
问题:
- 该模式的名称是什么?
- 我是以最正确的方式做的吗?我可以避免有一个静态变量吗?
不,我不认为您以最正确的方式进行操作,并且由于其中存在缺陷,我也不认为它确实是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();
}
可以通过用int允许嵌套悬架代替布尔来解决这个特定问题。如果值= 0。
(过去,我成功地使用了这样的模式来控制重复的redraws)
1。) m_suspending
是 CMyDoc
的属性,因为其行为取决于它。因此,它应该是CMyDoc
的成员变量。
2。)如果可以在多个线程中创建Suspender
,则应同步m_suspending
。无论如何,全局变量都很糟糕。
3。)raii是关键字,您的示例看起来与mutex
和lock_guard
交互的方式相似。
4。)您不需要每个微不足道的"模式"名称。RAII在C 中是基本的。
相关文章:
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 很好的语法来获取对向量/数组数据的大小引用?
- 我认为我的代码很好,但它在 cin a 之后停止并且没有进一步?
- 尽管一切看起来都很好,但值不会交换
- 为什么不同类型层次结构的指针之间的dynamic_cast定义得很好?
- 在 C++11 中利用 int*_t、int_fast*_t 和 int_least*_t 之间的差异的一个很好的例子是
- 对于短字符串来说,这是一个很好的哈希函数吗?
- 为什么指标有时效果很好,有时效果不佳?写下霍夫曼代码
- Red Hat:使用<atomic>编译很好,但链接器找不到__atomic_store_16;什么库?
- 使用移位的无符号数字作为数组的索引号是一种很好的做法
- 是否很好地使用状态模式来维护当前选定的对象?
- C++|以一种很好的方式将树(不一定是二进制的)打印到stdout
- 静态库单独使用很好,但在引用时会抛出错误
- 如果验证容器的大小并在同一条件语句下访问元素,这是很好的做法吗?
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 有没有办法关闭文件? fclose 不能很好地工作
- 引用的静态强制转换强制模板实例化,其中不完整的类型很好
- libc++:为什么流关闭后仍然很好
- 不能很好地运行HElib,但它建立在Windows 10 x64上
- 接口在C++中是一种很好的做法吗?