首页 > 解决方案 > 为什么工厂查找表上的“字段指向的内存可能泄漏”

问题描述

我正在尝试实现一个工厂,该工厂创建由公共基类Field继承的类型的新实例。

工厂被建模为返回 unique_ptr 的工厂函数的查找表。查找表的键类型是 string_view。

在工厂函数中,我为请求的类型调用 make_unique。

clang-analyzer 在返回 unique_ptr 时抱怨潜在的内存泄漏。

具有单个可用工厂条目的工厂查找表。

  using FieldFactory = std::function< std::unique_ptr< Field >( node const&, Clf const& ) >;

  static const std::unordered_map< std::string_view, FieldFactory > fieldFactoryLut = {
    {"static-text"sv, []( auto const& node, auto const& parent ) { return std::make_unique< StaticTextField >( node, parent ); }}
  };

用法

auto const& factoryFun = fieldFactoryLut.at("static-text"sv);
auto uPtr = factoryFun(node, clf);

通过调用 make_unique 我预计不会发生内存泄漏,但 clang-analyzer 声称:

warning: Potential leak of memory pointed to by field '_M_head_impl' [clang-analyzer-cplusplus.NewDeleteLeaks]
[build]     {"static-text"sv, []( auto const& node, auto const& parent ) { return std::make_unique< StaticTextField >( node, parent ); }}

谁能告诉我clang在这里看到了什么?

标签: memory-leaksc++17static-analysis

解决方案


推荐阅读