c++ - 将函数标记为 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
};
这也应该适用于铿锵声。还有一个变体可以使用 msvc 执行此操作,但我不知道它是否在我的头顶。
推荐阅读
- python - 比较两个不同大小的numpy数组的最佳方法
- html - 在 div 底部而不是 div 顶部显示框
- c# - 将数组中的元素右移 5
- c# - 如何将 OAuth 与 Office 365 报告 Web 服务结合使用
- c# - 为什么我不能在这里使用 SQLite 命令生成器?
- python - 使用多处理池在 python 中加速 TFLite 推理
- angular - 在 npm 上拆分和发布后如何维护 Angular 模块
- c# - 使用 C# 对象创建复杂的 JSON
- mql4 - MQL4 问题 如何在 EA 中打开多个订单
- docker - phpmyadmin 无法使用 docker-compose 连接到 mariadb:数据包乱序