TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
 
C++ Coding Standard
Search

Rule:  OAL#018Checked automatically with code checker

Synopsis:Don't forget to give scoped variables a name
Language:C++
Severity Level:1
Category:Object Allocation


Description:

If you don't give scoped variables a name, the corresponding anonymous object will be created and destroyed immediately, but not at the end of its scope (as it would be expected). This is extremely dangerous in RAII (Resource Allocation Is Initialization) patterns or SBRM (Scope-Bound Resource Management) patterns, where resource allocation and cleanup depends on object life time, e.g. when allocating heap memory, sockets, files, locks, etc.

Take a look at the following code:

void EventListenerHelper::ClearEvents()
{
    boost::mutex::scoped_lock(m_mutex);
    m_events.clear();
}

The field "m_mutex" is locked and released immediately after that, so that the clear() operation is actually not locked as expected.

It should have been something like

void EventListenerHelper::ClearEvents()
{
    boost::mutex::scoped_lock my_lock(m_mutex);
    m_events.clear();
}

instead. The scoped lock is now named "my_lock" and will remain alive until the end of the function scope.