铸造策略以避免“指针在明确定义的C++代码中不能为空”
问题描述:
最近的编译器,例如铛,抱怨如果一个函数测试“this”是否为NULL,因为这是非法的根据标准。铸造策略以避免“指针在明确定义的C++代码中不能为空”
我有一个程序,大量使用这个,并试图清理它。以下是一些不警告的例子 - 这些安全吗?有没有一种很好的方法来获得符合C++标准的 - > toAA和 - > toAB功能行为? (理想情况下不改变正在调用这些功能,并且相当快的代码 - 看到的测试,这是在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
,所以您的编译器没有发出警告,因此未触发其检测算法。但是这并不会使行为变得更加不明确。对于你所知道的,编译器可以省略警告,然后偷偷做出煎饼。
只需使用'return m_type == AB? ...' –
在'toAB'里面检查'this'。没有意义,因为这首先应该从合法的“this”中调用。 –
toAB旨在像动态转换一样工作 - 如果传递NULL,它必须返回NULL。这就是为什么它检查“这个”。 –