gpt4 book ai didi

c++ - 函数的属性是什么意思?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:17 24 4
gpt4 key购买 nike

这个 C++11 语法是什么意思?

[[ noreturn ]] void f () {
throw "error";
}

C++ 标准工作草案 n3797 指出,

The first declaration of a function shall specify the noreturn attribute if any declaration of that function specifies the noreturn attribute. If a function is declared with the noreturn attribute in one translation unit and the same function is declared without the noreturn attribute in another translation unit, the program is ill-formed; no diagnostic required.

函数的属性是什么意思?

最佳答案

函数由其名称、返回类型、形参列表及其类型定义。这些项构成函数的“接口(interface)”:它们对函数的调用者很重要,因为它们定义了调用它的方式。

另一方面,属性提供了一种方法来告诉编译器有关函数的其他信息,这些信息不会改变其接口(interface)。当编译器知道一个函数是

  • 一个中断处理程序,或者
  • 纯函数(即没有副作用或对任何类型状态的引用),或
  • 返回两次的函数(类似于fork),或者
  • 永不返回的函数等

编译器可以更好地优化代码,并提供额外的警告/静音不必要的警告。

例如,如果你写

main() {
f();
g();
}

并且f()被标记为noreturn,编译器会发出关于g()调用不可达的警告。

关于c++ - 函数的属性是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23449809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com