问题描述
我想要创建一个代表同步原语的所有权的类,如下所示:
class CCriticalSectionLock
{
public:
CCriticalSectionLock(CCriticalSection& cs):cs(cs)
{cs.Enter }
〜CCriticalSectionLock()
{cs.Leave(); }
private:
CCriticalSection& cs;
}
这看起来像是在函数中获取所有权的好方法,如果有多个退出点或异常。然而,它确实会引起一些细微的问题,关于编译器将何时评估各种东西。考虑以下用法:
int MyMethod(void)
{
not_locked // do something not under lock
CCriticalSectionLock myLock(someCriticalSection);
locked(); // do something under lock
return ...; //一些表达式
}
AFAIK,C ++生命周期规则将保证 not_locked()
将在之前被调用,并且 locked()
然而,我不是那么清楚的是,当被返回的表达式将被评估为相对于锁析构函数。是否保证在析构函数之前对表达式求值?我会这样认为,但我不是100%肯定,如果不是可以导致非常微妙,间歇,难以找到的错误!
确实,考虑下面的代码:
$ b $ b
int function(){
MyClass myObject;
// stuff
return 5 + myObject.getNumericalValue();
}
与 getNumericalValue()
一个简单的成员函数,它基于对成员变量的计算返回一个int。如果表达式在销毁 myObject
之后被评估,你将有未定义的行为,并且在return语句中使用locals是不可能的。 p>
在您的情况下,锁定将在之后被销毁。
<为了增加一些严格性,让我引用标准(§3.7.3/ 3,强调我):
对于一个函数,块的结束在语句。
I am thinking of making a class which represents ownership of a synchronization primitive, something like this:
class CCriticalSectionLock
{
public:
CCriticalSectionLock( CCriticalSection &cs ) : cs( cs )
{ cs.Enter(); }
~CCriticalSectionLock()
{ cs.Leave(); }
private:
CCriticalSection &cs;
};
This looks like a good way to be able to take ownership during a function and ensure ownership is released even if there are multiple exit points or exceptions. It does, however, raise some subtle issues about exactly when the compiler will have various things evaluated. Consider the following use:
int MyMethod( void )
{
not_locked(); // do something not under lock
CCriticalSectionLock myLock( someCriticalSection );
locked(); // do something under lock
return ...; // some expression
}
AFAIK, C++ lifetime rules would guarantee that not_locked()
would be called before the lock is taken, and that locked()
would be called while the lock is held.
However, what I am not so clear on is exactly when the expression being returned would be evaluated with respect to the point at which the lock destructor is called. Is it guaranteed that the expression will be evaluated before the destructor? I would think so but I'm not 100% sure, and if not it could lead to very subtle, intermittent, hard-to-find bugs!
If they weren't, that would be very problematic.
Indeed, consider the following code :
int function(){
MyClass myObject;
//stuff
return 5 + myObject.getNumericalValue();
}
with getNumericalValue()
a simple member function that returns an int based on computations on member variable. If the expression was evaluated after the destruction of myObject
, you would have undefined behavior, and using locals would be impossible in return statement (which isn't the case).
In your case, the lock will be destroyed after the evaluation of the return statement.
To add some strictness to that, let me quote the standard (§3.7.3/3, emphasis mine) :
The end of the block, for a function, is after the return statement.
这篇关于在评估函数返回值之前或之后销毁本地字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!