gpt4 book ai didi

c++ - 是否有 GCC 选项警告写入 `this-field` 而不是 `this->field` ?

转载 作者:IT老高 更新时间:2023-10-28 13:20:50 28 4
gpt4 key购买 nike

以下代码(包含一个恶性错误)使用 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;
}

我可以为编译器 (GCC 4.8) 添加哪些警告以避免这种错字?

链接问题:是否有任何选项可以强制(或警告)使用 this-> 访问成员变量/函数?

最佳答案

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 中的错误是误报,但这对于自动化工具来说很难判断,因为它需要知道 当宏 __EXCEPTIONS 未设置时,不应输入此站点的 catch block 。)

免责声明:我对 cppcheck 没有其他经验。

关于c++ - 是否有 GCC 选项警告写入 `this-field` 而不是 `this->field` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46319247/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com