1. Changelog
- 
     R1 - 
       Split the proposal of the new attribute (this paper) from proposing attributes on expressions. 
- 
       Change audience from EWGI to EWG. 
 
- 
       
- 
     R0 - 
       First submission 
 
- 
       
2. Motivation and Scope
[P0068R0] (and its subsequent [P0189R1] and [P1301R4]) introduced the 
The main use case for the 
Examples of such functions include:
- 
     Pure functions, that is, functions with no side effects, that are just called for their return value (example: std :: vector :: empty () 
 This is not merely a performance issue, but also a correctness one: functions and types that are poorly named (again,empty () 
- 
     Functions that return error codes or similar values that must be examined (and therefore used) for the calling code to be correct. 
 In this case, discarding the return value constitutes a logical bug in user code, and encouraging a warning from the implementation should make the user aware of their mistake.
- 
     Functions that return unmanaged objects that must be reclaimed in a special way (example: std :: allocator < T >:: allocate operator new 
 For these functions, accidentally discarding the return value incurs in resource leaks.
- 
     Functions that return manager objects that should be kept alive; for instance, RAII managers that need to be kept alive in the block in which the function is invoked. 
 Discarding the return value does not constitute any resource leak per se, but code "close" to the function call (e.g. in the same block) may operate under the false assumption that the manager (and thus the resource) is still alive/acquired.
 Examples of these functions are (after [P1771R1]) constructors of lock managers, where the constructed object itself should not get discarded, otherwise the following code would operate without the necessary mutex protection.
Still: in some scenarios it is useful to expressely discard the result of an expression, without having the implementation generating a warning in that case. Examples include:
- 
     Partial domains. A nodiscard function that returns an error code may also document that it will never fail under certain conditions (for instance, when certain values are passed as parameters). If the user is already checking that the parameters are in the non-failing domain, there is no need to use the return value; it can be safely discarded. 
 One could argue that the code could still consume the error code, and for instanceassert 
- 
     Legacy. A function may return a status code to indicate success or failure; then, later, its implementation evolves in a way such that it never fails (example: pthread_once 
- 
     Testing. We may want to call a nodiscard function in order to e.g. perform smoke testing, make sure that wide-contract functions don’t crash, and similar. In these cases we are simply not interested in the return value, yet we do not want a warning. 
This paper proposes a standard way to express the user’s intent to discard the value of an expression. Such a way is currently missing, and workarounds are employed instead.
2.1. What’s a discarded return value?
A "discarded return value" is formally defined as a discarded-value expression in [expr.context]/2. They are:
- 
     expressions appearing as expression-statement productions ([stmt.expr]/1); 
- 
     the left-side expression of the builtin comma operator ([expr.comma]/1); 
- 
     expressions explicitly converted to (cv-)void ([expr.static.cast]/6). 
    As per [dcl.attr.nodiscard]/4,
implementations are encouraged to emit warnings when a nodiscard
call (a call to a function marked 
2.2. Existing discarding strategies
There are currently two main strategies for discarding a value returned from a 
2.2.1. Cast to void 
   [dcl.attr.nodiscard]/4 states:
 Appearance of a nodiscard call as a potentially-evaluated discarded-value expression ([expr.prop]) is discouraged unless explicitly cast to void 
   This means that an explicit cast to 
[[ nodiscard ]] int f ( int i ); f ( 123 ); // warning here ( void ) f ( 123 ); // no warning void ( f ( 123 )); // no warning 
Using a cast to suppress the warning has several major shortcomings:
- 
     It is a total abuse of notation. A cast notation is used, although one does not intend perform any type conversion; the code is just using an "arcane" language rule (any expression can be converted to cv void [[ nodiscard ]] 
- 
     It is hard to explain to language novices why the cast works and what it means. 
- 
     It is hard to grep for in a codebase. Also, different codebases use slightly different spellings for the cast ( void ( x ) ( void ) x 
- 
     The very same notation is also used for [[ maybe_unused ]] 
- 
     The rationale for the discard can only be provided via comments, not in code, and therefore it’s hard/impossible to enforce rules that mandate such a rationale in a codebase. 
2.2.2. Assignment to std :: ignore 
   It is possible to utilize 
[[ nodiscard ]] int f ( int i ); std :: ignore = f ( 123 ); // return value isn’t discarded => no warning 
Nitpicking, at the moment 
This solution is also "blessed" by the C++ Core Guidelines ([ES.48]), which favor it over the cast to 
Still, we claim that this solution has a number of shortcomings:
- 
     It is not usable by generic code, since it requires the right-hand side of the assignment to yield a value. If the right-hand side expression evaluates to void 
- 
     It is not compatible with C. 
- 
     std :: ignore 
- 
     It is relatively verbose compared to the cast to void 
- 
     Again, the rationale as of why we want to discard the result value can only be provided in comments. 
2.3. A new attribute
We find both strategies suboptimal, and therefore in this paper we are proposing a novel one: the 
// returns an error code [[ nodiscard ]] int f ( int i ); f ( 123 ); // warning here [[ discard ( "f always succeeds with positive inputs" )]] f ( 123 ); // no warning 
Compared with the previous solutions:
- 
     [[ discard ]] [[ nodiscard ]] [[ nodiscard ( "reason" )]] [[ discard ( "reason" )]] 
- 
     It supports a reason, expressed right in the attribute. While a C++ compiler would not use the reason itself (because it won’t generate a warning), having a reason available is useful for users and other tooling. Specifically: - 
       since the whole [[ nodiscard ]] [[ nodiscard ( "reason" )]] 
- 
       having a reason can also be enforced by tooling (for instance, code checkers could ban the usage of [[ discard ]] 
 
- 
       
- 
     It works with generic code (one can discard void 
- 
     It does not require to pull components of the Standard Library for suppressing a language warning. 
- 
     It is perfectly compatible with C, and we would welcome its adoption by WG14 as well. 
- 
     It is only moderately more verbose than the cast to void 
2.4. Sampling existing codebases
A major compelling motivation for the 
Existing, widely used codebases feature cases where results are discarded without offering a motivation (in comments or commit messages). This makes it hard to understand "after the fact" if the code is correct, and what the intentions of the authors were.
Here’s a few examples found in the wild where we think using 
2.4.1. Google Test
In 
// In debug mode, the Windows CRT can crash with an assertion over invalid // input (e.g. passing an invalid file descriptor). The default handling // for these assertions is to pop up a dialog and wait for user input. // Instead ask the CRT to dump such assertions to stderr non-interactively. if ( ! IsDebuggerPresent ()) { ( void ) _CrtSetReportMode ( _CRT_ASSERT , _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG ); ( void ) _CrtSetReportFile ( _CRT_ASSERT , _CRTDBG_FILE_STDERR ); } 
It is not clear at all why the return values are being explictly
discarded; the functions themselves are not marked 
2.4.2. libfmt
The only occurences of discarded values in libfmt are in testing code,
where 
EXPECT_THROW_MSG ( ( void ) fmt :: format ( runtime ( "{0:+}" ), reinterpret_cast < void *> ( 0x42 )), format_error , "invalid format specifier" ); 
Here we want to discard the return value anyhow because we want to test
that the call throws a given exception. The cast could be replaced by
something like 
2.4.3. Qt
QDuplicateTracker < QString > known ; ( void ) known . hasSeen ( path ); do { // ... // more code that uses `known` // ... } while ( separatorPos != -1 ); 
This code is discarding the result of a false). What a casual reader may fail to realize is that
*
The alternative formulation is much more expressive:
QDuplicateTracker < QString > known ; [[ discard ( "Loop invariant: the path is known by the tracker" )]] known . hasSeen ( path ); 
This is another example:
Qt :: Orientation QGridLayoutEngine::constraintOrientation () const { ( void ) ensureDynamicConstraint (); return ( Qt :: Orientation ) q_cachedConstraintOrientation ; } 
2.4.4. Boost.Asio
The 
class posix_mutex { // [...] // Destructor. ~ posix_mutex () { :: pthread_mutex_destroy ( & mutex_ ); // Ignore EBUSY. } // Lock the mutex. void lock () { ( void ) :: pthread_mutex_lock ( & mutex_ ); // Ignore EINVAL. } // Unlock the mutex. void unlock () { ( void ) :: pthread_mutex_unlock ( & mutex_ ); // Ignore EINVAL. } }; 
What do the comments refer to? One may assume they refer to the reason
behind discarding the return value of 
But then, why isn’t the destructor also discarding the return value of 
This raises the suspicion that the comments may not refer to the reason of the discarding, but to a some more general property of the operations: the error cannot be generated given the class' invariants. This would be something better expressed via assertions/contracts.
3. Design Decisions
3.1. Is [[ discard ]] 
   Based on the current usages of casting to 
// function call whose result we want to discard [[ discard ( "f never fails with positive numbers" )]] f ( 42 ); 
In this case the C++ grammar is already ruling that the attribute
appertains to the statement. For this reason we are proposing that
the 
If that expression contains multiple discarded-value expressions (by means of operator comma), the attribute will apply to them all, suppressing all their possible warnings:
[[ discard ]] a (), b (), c (); // don’t generate discarding warnings 
What about applying 
We are authoring a different proposal (P3093) that would enable attributes on expressions; with that proposal, in principle one could write:
a (), ([[ discard ]] b ()), c (); 
and only suppress discarding warnings for the call to 
Supporting 
Still, some scenarios where 
- 
     in a constructor’s member initialization list; 
- 
     as the increment (third) parameter of a for 
For instance:
for ( int i = 0 ; i < N ; ++ i , ([[ discard ]] f ( i ))) doSomething ( i ); 
We therefore plan to add support for discarding expressions, should attributes on expressions become possible.
3.2. Can void 
   Yes. We believe that such a situation can happen in practice, for instance in generic code, and such a restriction sounds therefore unnecessary and vexing.
3.3. What should happen if [[ discard ]] 
   Or, more in general, if it is applied to a statement that does not contain a nodiscard call?
For example:
[[ nodiscard ]] int f (); [[ discard ]] a = f (); // This is not *actually* discarding. Should it be legal? bool g (); // This is not marked as [[nodiscard]] [[ discard ]] g (); // Legal? 
Should we accept or forbid these usages, as the attribute is
meaningless (at best) or misleading (at worst)?
We are proposing to accept the code, under the rationale that the
attribute serves to suppress a 
Of course implementations can still diagnose "questionable" usages as QoI.
3.4. Bikeshedding: naming
The most obvious name for the attribute that we are proposing is 
There is a possible objection to this name: this attribute does not actually "force" the value of an expression to be discarded:
[[ discard ]] result = f (); // nothing is discarded here 
One could therefore prefer a more nuanced form, such as 
[[ may_discard ]] f (); // actually discarding [[ may_discard ]] result = f (); // not discarding 
We would like to request a poll to EWG.
4. Impact on the Standard
This proposal is a core language extension. It proposes a new standard
attribute, spelled 
No changes are required in the Standard Library.
5. Technical Specifications
All the proposed changes are relative to [N4971].
5.1. Proposed wording
In [cpp.cond] append a new row to Table 21 ([tab:cpp.cond.ha]):
| Attribute | Value | 
|---|---|
|  |  | 
with 
In [dcl.attr.nodiscard] insert a new paragraph after 3:
4. A potentially-evaluated discarded-value expression ([expr.prop]) which is a nodiscard call and which is neitheris a discouraged nodiscard call.
explicitly cast to
([expr.static.cast]), orvoid 
an expression (or subexpression thereof) of an expression-statement marked with the
attribute ([dcl.attr.discard])discard 
Renumber and modify the existing paragraph 4 as shown:
4.5. Recommended practice:Appearance of a nodiscard call as a potentially-evaluated discarded-value expression ([expr.prop]) is discouraged unless explicitly cast to. Implementations should issue a warningvoid in such casesfor discouraged nodiscard calls . [...]
And renumber the rest of the paragraphs in [dcl.attr.nodiscard].
Modify the Example 1 as shown (including only the lines for the chosen approach):
struct [[ nodiscard ]] my_scopeguard { /* ... */ }; struct my_unique { my_unique () = default ; // does not acquire resource [[ nodiscard ]] my_unique ( int fd ) { /* ... */ } // acquires resource ~ my_unique () noexcept { /* ... */ } // releases resource, if any /* ... */ }; struct [[ nodiscard ]] error_info { /* ... */ }; error_info enable_missile_safety_mode (); void launch_missiles (); void test_missiles () { my_scopeguard (); // warning encouraged ( void ) my_scopeguard (), // warning not encouraged, cast to void launch_missiles (); // comma operator, statement continues my_unique ( 42 ); // warning encouraged my_unique (); // warning not encouraged enable_missile_safety_mode (); // warning encouraged launch_missiles (); [[ discard ]] my_unique ( 123 ); // warning not encouraged [[ discard ( "testing illegal fds" )]] my_unique ( -1 ); // warning not encouraged [[ discard ]] my_unique (); // warning not encouraged [[ discard ]] my_unique (), enable_missile_safety_mode (); // warning not encouraged } error_info & foo (); void f () { foo (); } // warning not encouraged: not a nodiscard call, because neither // the (reference) return type nor the function is declared nodiscard 
Add a new subclause at the end of [dcl.attr], with the following content:
??? Discard attribute [dcl.attr.discard]
The attribute-token
may be applied to an expression-statement. An attribute-argument-clause may be present and, if present, shall have the form:discard unevaluated-string( ) 
Recommended practice: Implementations should suppress the warning associated with a nodiscard call ([dcl.attr.nodiscard]) if such a call is an expression (or subexpression thereof) of an expression-statement marked as
. The value of a has-attribute-expression for thediscard attribute should bediscard unless the implementation can suppress such warnings.0 
The unevaluated-string in a discard attribute-argument-clause is ignored.
[Note 1: the string is meant to be used in code reviews, by static analyzers and in similar scenarios. — end note]
6. Acknowledgements
Thanks to KDAB for supporting this work.
All remaining errors are ours and ours only.