我有一个不会改变任何东西的函数。函数指针是类似函数指针数组的一部分,不能标记为 const,因为那样它就不能成为该数组的一部分。
我有一个处于事件状态的编译器标志,它会警告我某个函数是否有可能被声明为 const。这会导致对该函数发出警告。
我使用 g++-10 和 -Wsuggest-attribute=const 等。
我已经查看了我可能可以使用的属性,但没有一个可以满足我的要求。
如何抑制该函数的编译器警告,同时保持其他函数的警告标志处于事件状态?
#include <iostream>
#include <vector>
#include <string>
class C
{
public:
struct S
{
std::string fname;
void (C::*fptr)(void) = nullptr;
};
private:
std::vector<S> vec;
int data;
// can't be const, alters data -> can't update function pointer definition in struct
void f1();
void f2();
// -Wsuggest-attribute=const marks this as candidate
// but doing so will break assignment of vec
void f3();
public:
C() : data{0} {
vec = { {"inc", &C::f1}, {"dec", &C::f2}, {"nop", &C::f3} };
}
virtual ~C() { /* Empty */ }
int getData() const;
void exec(uint8_t opcode);
};
void C::f1() { data++; }
void C::f2() { data--; }
void C::f3() { return; }
int C::getData() const { return data; }
void C::exec(uint8_t opcode) { (this->*vec[opcode].fptr)(); }
int main()
{
C c;
c.exec(0);
std::cout << c.getData() << std::endl;
return 0;
}
我不知道为什么这个例子没有产生警告。但实际代码确实如此。
最佳答案
您可以使用编译指示暂时禁用 gcc 和 clang 中的警告:
class C
{
// First save state of warnings
#pragma GCC diagnostic push
// Then ignore warning for this function
#pragma GCC diagnostic ignored "-Wsuggest-attribute=const"
void f3(){}
// Lastly restore warning state
#pragma GCC diagnostic pop
};
这也适用于 clang。还有一个使用 msvc 执行此操作的变体,但我不知道它的意思。
关于c++ - 将函数标记为 const 的非候选函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65922475/