避免"pointer cannot be null in well-defined C++ code"的投射策略

Casting policies to avoid "pointer cannot be null in well-defined C++ code"

本文关键字:code 策略 C++ in cannot pointer be null 避免 well-defined      更新时间:2023-10-16

最近的编译器,例如clang,如果一个函数测试"this"是否为NULL,就会报错,因为根据标准,这是非法的。

我有一个程序大量使用了这个,我正在努力清理它。下面是一些没有警告的例子——这些安全吗?是否有一个好的方法来获得->toAA和->toAB功能行为是c++标准兼容的?(理想情况下,不需要更改调用这些函数的代码,并且速度相当快——请参阅下面的注释,在GCC 4.6中测试该函数会更快。)

#include <stddef.h>
class ClassAA;
class ClassAB;
class ClassBase {
public:
  enum Type {AA, AB};
  Type m_type;
  ClassAA* toAA();
  ClassAB* toAB();
  ClassBase(Type t) : m_type(t) {}
  virtual ~ClassBase() {}
};
class ClassAA : public ClassBase { public: int a; ClassAA():ClassBase(AA) {} };
class ClassAB : public ClassBase { public: int b; ClassAB():ClassBase(AB) {} };
// toAA and toAB are intended to have same function,
// but toAB is significantly better performing on GCC 4.6.
inline ClassAA* ClassBase::toAA() { return dynamic_cast<ClassAA*>(this); }
inline ClassAB* ClassBase::toAB() { return (this && m_type == AB) ? static_cast<ClassAB*>(this) : NULL; }
int foo(ClassBase* bp) {
    if (bp && bp->toAA())   // Legal
    return -1;
    if (dynamic_cast<ClassAA*>(bp))   // Legal
    return -1;
    if (!bp->toAA())             // No warning, is this legal?
    return -1;
    if (bp->toAA()->a)     // No warning, is this legal?
    return 10;
    if (bp->toAB()->b)     // Warning due to use of "this", illagal presumably
    return 20;
    return 0;
}

让它们成为自由函数,或者接受实参的static成员。

非静态成员函数必须在现存对象上调用;时期。

你的编译器不可能发出警告,因为你没有解引用this,所以它的检测算法不会被触发。但这并没有减少行为的不确定性。编译器可能会忽略警告,然后偷偷地去做煎饼,你知道的。