这段代码(包含恶性漏洞)在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 ->
访问成员变量/函数?
this->
。这将完全避免问题。 - phuclv