mark function as non-candidate for const

Viewed 72

I have a function that doesn't alter anything. The function pointer part of an array of similar function pointers and can't be marked as const as it will not be able to be part of that array then.

I have a compiler flag active that warns me if a function is a potential candidate for being declared const. And that is causing a warning to be given for that function.

I use g++-10 with -Wsuggest-attribute=const among other things.

I've had a look at attributes that I might be able to use, but there are none that do what I want.

How do I suppress the compiler warning for that function while keeping the warning flag active for other functions?

#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;
}

I don't know why this example doesn't produce the warning. But the actual code does.

1 Answers

You can temporarily disable warnings in gcc and clang with a pragma:

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
};

This should also work for clang. There is also a variant to do this with msvc, but I don't know it of the top of my head.

Related