std::map uses a non-inline function to rebalance its tree and the
compiler can't see that it always returns a valid pointer (assuming
valid inputs, which is a precondition anyway). This can result in
-Wnull-derefernce warnings for valid code, because the compiler thinks
there is a path where the function returns null.
Adding the returns_nonnull attribute tells the compiler that is can't
happen. While we're doing that, we might as well also add a nonnull
attribute to the rebalancing functions too.
libstdc++-v3/ChangeLog:
PR libstdc++/108554
* include/bits/stl_tree.h (_Rb_tree_insert_and_rebalance): Add
nonnull attribute.
(_Rb_tree_rebalance_for_erase): Add nonnull and returns_nonnull
attributes.
* testsuite/23_containers/map/modifiers/108554.cc: New test.
_Base_ptr _M_node;
};
+ __attribute__((__nonnull__))
void
_Rb_tree_insert_and_rebalance(const bool __insert_left,
_Rb_tree_node_base* __x,
_Rb_tree_node_base* __p,
_Rb_tree_node_base& __header) throw ();
+ __attribute__((__nonnull__,__returns_nonnull__))
_Rb_tree_node_base*
_Rb_tree_rebalance_for_erase(_Rb_tree_node_base* const __z,
_Rb_tree_node_base& __header) throw ();
--- /dev/null
+// { dg-do compile { target c++17 } }
+// { dg-options "-Wnull-dereference -O2" }
+
+// PR libstdc++/108554
+// Warning from -Wnull-dereference when extracting a unique_ptr from a map.
+
+#include <map>
+#include <memory>
+#include <string>
+
+int pop(std::map<std::string, std::unique_ptr<int>>& m)
+{
+ if (auto it = m.find("key"); it != m.end())
+ {
+ auto item = std::move(m.extract(it).mapped());
+ return *item;
+ }
+ return 0;
+}