C++ rule for dereferencing shared_ptr acquired by std::weak_ptr::lock()

Hello,

I recently ran into a bug where a std::shared_ptr was being dereferenced without a prior check that it was non-null.

This shared_ptr was constructed from calling lock() on a weak_ptr: https://en.cppreference.com/w/cpp/memory/weak_ptr/lock

I was surprised to see that SonarQube did not flag this as a potential bug (failing to check for nullptr before dereferencing the shared_ptr that was acquired by locking a weak_ptr).

Example Code:

class Example {
Example(std::shared_ptr<Foo> dependency) 
    : m_weakPtr(dependency) {
}

private:
void doSomething() {
    // Foo dependency may or may not exist at this point, might have been deallocated by now.
    const std::shared_ptr<Foo> foo = m_weakPtr.lock();
    foo->bar();
}

std::weak_ptr<Foo> m_weakPtr;
}

Hello @adenisonafifi,

You are right that this is not a good coding pattern. We have a rule that deals with null pointer dereference, but it is not triggered in this situation. Since the pattern on how to use weak_ptr is pretty specific, we could also have a dedicated rule.

I created a ticket to improve this situation.

Thank you for reporting it.