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))
?
Asked
Active
Viewed 298 times
2

Nordlöw
- 11,838
- 10
- 52
- 99
-
Err, what's the point? When will an average well-formed program going to invoke a c'tor for the same object twice? – StoryTeller - Unslander Monica Nov 19 '18 at 13:09
-
Ahh, I didn't think of the fact that it creates/allocates a new instance. I guess it's not relevant to qualify constructors then. – Nordlöw Nov 19 '18 at 13:11
1 Answers
2
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.

P.W
- 26,289
- 6
- 39
- 76