C++ 类构造函数限定为 __attribute__((pure)) 或 __attribute__((const))

标签 c++ attributes pure-function

如果 C++ 类构造函数只能通过其参数访问数据,那么它们是否可以并且应该声明 __attribute__((pure))?在什么情况下它们应该被限定为__attribute__((const))

最佳答案

当您将构造函数限定为 pureconst 时,GCC 会发出警告。这是因为构造函数不返回任何内容(返回 void),并且在此类上拥有 pureconst 属性没有多大意义。功能。

查看 godbolt 演示 here .

<source>:3:30: warning: 'pure' attribute on function returning 'void' [-Wattributes]
     A()  __attribute__((pure));

                              ^
<source>:8:31: warning: 'const' attribute on function returning 'void' [-Wattributes]
     B()  __attribute__((const));                               ^

来自海湾合作委员会documentation :

const
...
Because a const function cannot have any side effects it does not make sense for such a function to return void. Declaring such a function is diagnosed.

pure
...
Because a pure function cannot have any side effects it does not make sense for such a function to return void. Declaring such a function is diagnosed.

关于C++ 类构造函数限定为 __attribute__((pure)) 或 __attribute__((const)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53375307/

相关文章:

c++ - 从协方差矩阵中找出概率椭圆

c++ - 有没有办法在不使用 Friend 类(C++)的情况下防止从另一个类使用公共(public)函数

java - 使用 SOAP 和 Java 添加 xmlns 命名空间的问题

sorting - Magento 1.9.1 不按位置对可配置产品属性下拉列表进行排序

c# - 如何在模型和 View 模型中使用 "DRY up"C# 属性?

Haskell:陷入 IO monad 困境

C++ 跨平台 zlib simplifer-wrapper

c++ - “AMA::MyProduct”:无法实例化抽象类

c++ - 海湾合作委员会错误 : function might be candidate for attribute ‘pure’ if it is known to return normally

c++ - 将函数声明为 pure 或 const 对 GCC 的影响(如果不是)