如果 C++ 类构造函数只能通过其参数访问数据,那么它们是否可以并且应该声明 __attribute__((pure))
?在什么情况下它们应该被限定为__attribute__((const))
?
最佳答案
当您将构造函数限定为 pure
或 const
时,GCC 会发出警告。这是因为构造函数不返回任何内容(返回 void
),并且在此类上拥有 pure
或 const
属性没有多大意义。功能。
查看 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/