(core) use [[nodiscard]] attribute for weak_ptr::lock()
Description
Currently, weak_ptr::lock() can be chained with ->
operator leaving the object unlocked once the statement is executed, introducing race conditions and hard to find bugs linked to concurrency problems. Furthermore, weak_ptr::lock() can return a null pointer if the weak pointer is expired. Consider this code:
// m_weak is a weak_ptr...
if(m_weak.lock()->empty())
{
// m_weak is no more protected and can be modified outside !
// Possible race conditions and concurrency problems
m_weak.lock()->doSomething();
}
Should be modified in:
// m_weak is a weak_ptr...
auto locked = m_weak.lock();
// We also test for weak pointer expiration
if(locked && locked->empty())
{
// m_weak is still locked
// No race conditions and concurrency problems
locked->doSomething();
}
Proposal
We may use the [[nodiscard]] c++17 attribute to ensure that the locked_ptr holding the lock is not discarded. This will force people to store it to a local variable by issuing a warning if this is not the case.
Links / references
https://en.cppreference.com/w/cpp/language/attributes/nodiscard