避免"pointer cannot be null in well-defined C++ code"的投射策略
Casting policies to avoid "pointer cannot be null in well-defined C++ code"
最近的编译器,例如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
,所以它的检测算法不会被触发。但这并没有减少行为的不确定性。编译器可能会忽略警告,然后偷偷地去做煎饼,你知道的。
相关文章:
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- Visual Studio Code - C++ Debugger 無法啟動
- Visual Studio Code "undefined reference to `WinMain@16'"
- C++17中的并行执行策略
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- 使用VS Code和CMake Tools运行自定义命令
- 修改 VS Code 中的默认C++代码段
- 运行时执行策略不同
- 编译器上的策略数据结构不起作用
- 如何配置Visual Studio Code以使用cygwin,cmake和gcc进行调试
- 我应该在简单的策略游戏中为各个派系使用类吗 - C++
- std::to_string - 'to_string' 不是 'std' 的成员 - Visual Studio Code 1.42.0
- VS Code C++:不准确的系统包括路径错误(wchar.h,boost/lambda/lambda.hpp)
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- C++新手,想知道如何使用VS code 2019播放音频文件
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- 如何在Visual Studio Code中重命名我的a.exe文件?
- C++ Visual Studio Code 的设置不起作用
- 没有执行策略的 std::transform_reduce 是可移植的吗?
- 避免"pointer cannot be null in well-defined C++ code"的投射策略