https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100047
Bug ID: 100047 Summary: False -Wmaybe-uninitialized on one var depending on type of other var Product: gcc Version: 11.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: gccbugbjorn at fahller dot se Target Milestone: --- With the following C++17 code, there's a warning that m_size can be used uninitialized if m_ptr is a std::unique_ptr<>, but not if it is a raw pointer. This only happens when some optimization is enabled. -Og is enough. The bug also applies to gcc-10, gcc-9 and gcc-8 (have not checked older versions). #include <cstdint> #include <cstdlib> #include <optional> #include <memory> #include <string> #if EXPOSE_BUG using buffer_ptr = std::unique_ptr<uint8_t>; #else using buffer_ptr = const uint8_t*; #endif const uint8_t* get(const std::unique_ptr<uint8_t>& ptr) { return ptr.get(); } const uint8_t* get(const uint8_t* ptr) { return ptr; } class packet_buffer { public: using const_iterator = const uint8_t*; packet_buffer() : m_ptr(nullptr), m_size(0) {} packet_buffer(buffer_ptr ptr, uint16_t size) : m_ptr(std::move(ptr)), m_size(size) { } size_t size() const { return m_size; } // <- here const uint8_t* data() const { return get(m_ptr); } const_iterator begin() const { return data(); } const_iterator end() const { return data() + size(); } private: buffer_ptr m_ptr; uint16_t m_size = 0; }; std::string func() { auto f = [](std::optional<packet_buffer> result) { auto&& b = result.value(); return std::string(b.begin(), b.end()); }; return f(std::nullopt); } Godbolt link: https://godbolt.org/z/63z8qzcxv