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

308 views Asked by At

Can and should C++ class constructors be declared __attribute__((pure)) if they only can reach data via its parameters? And in which cases should they be qualified as __attribute__((const))?

1

There are 1 answers

0
P.W On BEST ANSWER

GCC warns when you qualify constructors as pure or const. This is because a constructor does not return anything (returns void) and it does not make much sense to have a pure or const attributes on such functions.

See godbolt demo 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));                               ^

From 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.