Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should C++ attributes be in the header or the implementation or both?

Tags:

c++

I have looked around quite a bit and have not found whether or not C++ attributes should be in the header or the implementation or both. For example:

file.h

[[nodiscard]] std::future<int> get_data();

file.cpp

[[nodiscard]] std::future<int> get_data() { return ...; }

Should both have the attribute or only one? The examples provided by cppreference are all functions with no forward declaration.

like image 291
Michael Smith Avatar asked Mar 30 '18 17:03

Michael Smith


1 Answers

To be effective, the attribute needs to be applied to the declaration (i.e., in the header). If a call is being compiled, and the declaration the compiler has seen lacks the attribute, the compiler normally won't be able to issue a diagnostic based on the attribute (since it hasn't seen it).

§[dcl.attr.nodiscard]/1:

The attribute-token nodiscard may be applied to the declarator-id in a function declaration or to the declaration of a class or enumeration.

The same basic notion applies to most other attributes as well, but a few belong in the implementation--most obviously the [[fallthrough]] attribute, which goes at the end of a case in a switch statement, so it has to be located where the switch statement itself is.

The [[noreturn]] attribute is a little bit more specific. It directly requires that if a function is declared more than once, the first declaration the compiler sees for that function must have the [[noreturn]] attribute. If the compiler sees a [[noreturn]] attribute on a function that has previously been declared without it, the code is ill-formed (but no diagnostic is required if the two declarations were in separate translation units).

like image 68
Jerry Coffin Avatar answered Nov 15 '22 17:11

Jerry Coffin