Qt noreturn 属性添加

Qt noreturn 属性添加

*.cpp:21:1: warning: function ‘f’ could be declared with attribute ‘noreturn’

解决Qt去警告: could be declared with attribute 'noreturn’的方法在函数声明的地方前加
[[noreturn]]
例如:

//h文件
[[noreturn]] void test();
//cpp文件
void test(){};

原理:

The items between [[ ]] in a function (variable…) declaration are attributes that provide the compiler with extra information about the item they are attached to. The compiler can use these in a range of ways. The “noreturn” attribute has been around since C++ 11.

[[ noreturn ]] attached to a function declaration informs the compiler that control will not return from the function (as in the case of an unconditional throw()). They go in the first declaration of the function. If f() is declared in a header file then this is the place to put it. If the function exists only in a single CPP file, i.e. it is private, with no other declaration then it goes there.

The second code snippet you posted is an example that can lead to undefined behaviour, i.e. returning from a function you explicitly declared would not return control.

// >>> function.h
#ifndef FUNCTION_H
#define FUNCTION_H
 
[[ noreturn ]] void f();
void g();
 
#endif // FUNCTION_H
 
// >>> function.cpp
#include <iostream>
using namespace std;
 
#include "function.h"
 
void f() {
    cout << "No return" << endl;
    throw 1;
}
 
void g() {
    cout << "No return" << endl;;
    throw 1;
}
 
// >>> main.cpp
#include <iostream>
using namespace std;
 
#include "function.h"
 
[[ noreturn ]] void h() {
    cout << "No return" << endl;
    throw 3;
}
 
int main(int argc, char **argv) {
    cout << "Before f()" << endl;
    f();
    // this should be unreachable code
    cout << "Before g()" << endl;
    g();
    cout << "Before h()" << endl;
    h();
}

Functions f() and g() have identical function code but, because the compiler knows that f() will not return, it may generate different code for these function or calls to them. In my experiments with GNU C++ there is no code generated for the calls to g() and h() because they cannot be reached after a call to f().

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值