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

C++ class constructors qualified as __attribute__((pure)) or __attribute__((const))

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

当您将构造函数限定为 pureconst 时,GCC 会发出警告。这是因为构造函数不会 return 任何东西 (returns 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));                               ^

来自 GCC 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.