通过 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/