c++ - 为什么Boost.Concept通过空指针调用析构函数?

标签 c++ boost c++11 clang-static-analyzer c++-concepts

通过 Clang 静态分析器分析一些 Boost 相关代码时,出现以下错误:

Logic error Called C++ object pointer is null usage.hpp 22

来自boost/concept/usage.hpp中的以下代码

template <class Model>
struct usage_requirements
{
    ~usage_requirements() { ((Model*)0)->~Model(); }
};

问题:这是 Boost 中真正的错误,还是 Boost.Concept 通过空指针调用析构函数以某种方式在概念检查期间生成编译器错误?

最佳答案

*免责声明。对此持保留态度,我绝不是 Boost Concept 专家。

它用于使编译器实例化“模型”析构函数,以使编译器因概念失败而生成错误。

usage_requirements 与创建新概念时使用的 BOOST_CONCEPT_USAGE 一起使用,请参阅 Creating Concepts在文档中。

#   define BOOST_CONCEPT_USAGE(model)                                    \
      model(); /* at least 2.96 and 3.4.3 both need this :( */           \
      BOOST_CONCEPT_ASSERT((boost::concepts::usage_requirements<model>)); \
      ~model()

其用法如下:

BOOST_CONCEPT_USAGE(InputIterator)
{
    X j(i);             // require copy construction
    same_type(*i++,v);  // require postincrement-dereference returning value_type
    X& x = ++j;         // require preincrement returning X&
}

最终会是这样的:

model(); /* at least 2.96 and 3.4.3 both need this :( */           \
BOOST_CONCEPT_ASSERT((boost::concepts::usage_requirements<model>)); \
~model()
{
    X j(i);             // require copy construction
    same_type(*i++,v);  // require postincrement-dereference returning value_type
    X& x = ++j;         // require preincrement returning X&
}

如您所见,概念需求最终出现在 model 析构函数中。这就是为什么我们需要欺骗编译器来实例化它。

关于c++ - 为什么Boost.Concept通过空指针调用析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17485520/

相关文章:

c++ - 当我可以将 RNG 传递给分布时,为什么要使用 variate_generator? (特别是 C++ 和 Boost)

c++ - 如何使用可变模板参数调用模板函数?

c++ - 如何在没有删除运算符的情况下为堆对象调用析构函数?

c++ - 在模板化类中定义模板化类的静态数据成员

c++ - 将 STL 容器与 boost 范围适配器一起使用时出现 value_type 错误

c++ - 使用 std::enable_if 时的对象切片

c++ - 我可以在移动赋值运算符中调用析构函数吗?

c++ - 从 C++ 静态库中删除除 API 之外的所有内容?

c++ - 合并两个已排序的链表

c++ - Boost::Container::Vector with Enum Template Argument - 不是合法的基类