Cad*_*hon 62 c++ gcc gcc-warning
以下代码(包含恶意错误)在没有任何警告的情况下编译GCC.但是,当然,它不像开发人员(我)那样工作.
#include <iostream>
struct A
{
bool b;
void set(bool b_) { this->b = b_; }
bool get() const { return this-b; } // The bug is here: '-' instead of '->'
};
int main()
{
A a;
a.set(true);
std::cout << a.get() << std::endl; // Print 1
a.set(false);
std::cout << a.get() << std::endl; // Print 1 too...
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我可以为编译器添加哪个警告(GCC 4.8)以避免这种错误?
链接问题:是否有任何强制(或警告)访问成员变量/函数的选项this->?
Arn*_*gel 71
通过cppcheck以下方式检测此特定问题:
$ cppcheck --enable=all this-minus-bool.cxx Checking this-minus-bool.cxx... [this-minus-bool.cxx:7]: (warning) Suspicious pointer subtraction. Did you intend to write '->'? (information) Cppcheck cannot find all the include files (use --check-config for details)
这没有给出包含路径.如果我添加-I /usr/include/c++/4.8/,仍会检测到该问题:
Checking this-minus-bool.cxx... [this-minus-bool.cxx]: (information) Too many #ifdef configurations - cppcheck only checks 12 of 45 configurations. Use --force to check all configurations. [this-minus-bool.cxx:7]: (warning) Suspicious pointer subtraction. Did you intend to write '->'? [/usr/include/c++/4.8/bits/ostream.tcc:335]: (style) Struct '__ptr_guard' has a constructor with 1 argument that is not explicit. [/usr/include/c++/4.8/bits/locale_classes.tcc:248]: (error) Deallocating a deallocated pointer: __c
然后cppcheck慢慢地通过上述#ifdef配置工作.
(作为旁注,错误local_classes.tcc是误报,但这很难说是一个自动化工具,因为它需要知道catch在未__EXCEPTIONS设置宏时不应输入此站点上的块.)
免责声明:我没有其他cppcheck经验.
Bat*_*eba 32
否,this - b正在执行指针运算上的指针this,尽管,b作为一个bool类型(b隐式转换为int).
(有趣的是,你总是可以设置一个类型this + b的指针,因为你可以设置指向标量末尾的指针!所以即使你最喜欢的未定义的行为观察者也会允许那个.)bbool
数组边界检查一直是C++程序员的工作.
另请注意,在您的情况下使用this是多余的:因此减少这种过度使用是解决问题的一种方法.
Sim*_*mon 13
我想建议另一种工具(除了cppcheck@ arne-vogel提出的),提供更好的视觉辅助,而不是要求的警告:
使用clang-format自动格式化代码.结果可能看起来像这样(取决于设置),通过添加的空间使bug更加明显operator-:
struct A {
bool b;
void set(bool b_) { this->b = b_; }
bool get() const { return this - b; }
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5084 次 |
| 最近记录: |