您只需要将变量的定义与需要保护的写访问权限分开,特别是因为写到左边(通过您自己的语句)的部分不是重点。
为了确保变量不会从不一致的读取中获取值,只需在锁内部进行读取就足够了,而锁又不需要在初始化时进行,这使编译器感到恼火。
所以:
int some_function()
{
/* ... */
int nonconst = 0; /* no declaration is after statement */
lock ( ...)
nonconst = test_variable[INDEX]; /* only assignment,no declaration */
/* ... */
{ /* start a new block to solve the compilers sequence complaint */
const int var = nonconst; /* var itself is const */
/* ... */
/* var being used sometime later,no code can change var */
/* changing the nonconst variable is possible,but does not affect
the value of var anymore */
/* ... */
}
unlock(...)
}
以上是我的答案,请在下面找到一个更优雅的版本,据我了解,该版本是OP根据Adrian Mole的有洞察力的评论(我盲目地遗漏了……)和我的答案的结构得出的。如果Adrian或OP做出自己的回答并通知我,我将删除此部分。目前,它可以改善此答案,为他人带来好处。
int some_function()
{
/* ... */
lock ( ...);
{ /* start a new block to solve the compilers sequence complaint */
const int var = test_variable[INDEX]; /* var itself is const */
/* ... */
/* var being used sometime later,no code can change var */
/* ... */
}
unlock(...);
}
我做了一些微小的编辑,以减少混乱和编译器警告。
本文链接:https://www.f2er.com/2669742.html