I've got a class, which allocates some resource in constructor and releases it in destructor. For example a critical section. Let's call it class CriticalSection
. I create a variable at the beginning of a critical block of code, and it gets deleted at the closing brace:
void Worker::Work()
{
// some work goes here
....;
// the critical block
{
CriticalSection cs(aReferenceToTheLock);
// some critical work here
.....;
} // <-- destruction of cs, the lock gets released
// further unprotected code
....;
}
Well, that's how it should be done. Alas, a little omission occured:
{
CriticalSection(aReferenceToTheLock);
// some work here
.....;
}
There is no cs
variable name! As a result the constructor invocation creates a temporary, anonymous variable which gets destroyed immediately, just at the semicolon which closes the line. And the whole block is not protected anymore.
Can this kind of error be detected? Is there any specific warning I should enable in gcc or msvc compiler?