首页 > 解决方案 > 将函数标记为 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;
}

我不知道为什么这个例子没有产生警告。但实际代码确实如此。

标签: c++constantscompiler-warnings

解决方案


您可以使用编译指示暂时禁用 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
};

这也应该适用于铿锵声。还有一个变体可以使用 msvc 执行此操作,但我不知道它是否在我的头顶。


推荐阅读