将函数标记为 const 的非候选对象

问题描述

我有一个不会改变任何东西的函数。类似函数指针数组的函数指针部分,不能被标记为 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 执行此操作的变体,但我不知道。