Is it correct that
if (std::lock_guard lk(m_state.mtx); true) {
m_state.aborting = true;
}
and
{
std::lock_guard lk(m_state.mtx)
m_state.aborting = true;
}
are 100% identical?
Here is the background on my question: In Mastering the C++17 STL, the author gives a code example for a thread pool. It contains the following block (page 208):
~ThreadPool() {
if (std::lock_guard lk(m_state.mtx); true) { // <<--- Line of interest
m_state.aborting = true;
}
m_cv.notify_all();
for (std::thread& t : m_workers) {
t.join();
}
}
The marked line uses the initializer part of an if-statement to create the lock_guard. This has been used in other questions in order to limit the scope of the lock_guard to the if-statement while also protecting the evaluation of the if-statement itself.
What confuses me in this example is that the if statement has no proper condition. According to the cppreference page on if,
If init-statement is used, the if statement is equivalent to
{ init_statement if ( condition ) statement-true }
In this case, this would mean that if (std::lock_guard lk(m_state.mtx); true) {...}
is equivalent to
{
std::lock_guard lk(m_state.mtx);
if (true) {
m_state.aborting = true;
}
}
Am I missing either a case where this is not 100% identical or a good reason why it has been written with an if-statement?
The same pattern is used in a different example on the next page, so I think that it was done on purpose and not a leftover from when there was an actual condition.