From 81b87b7b367a022611b6e881eb519dba43c7c5c4 Mon Sep 17 00:00:00 2001 From: Fred Tingaud <95592999+frederic-tingaud-sonarsource@users.noreply.github.com> Date: Thu, 27 Jun 2024 11:31:01 +0200 Subject: [PATCH] Modify rule S2807: Add a longer explanation of the hidden friend pattern --- rules/S2807/cfamily/rule.adoc | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/rules/S2807/cfamily/rule.adoc b/rules/S2807/cfamily/rule.adoc index 2fdb9633ddd..9e44d6efb18 100644 --- a/rules/S2807/cfamily/rule.adoc +++ b/rules/S2807/cfamily/rule.adoc @@ -3,7 +3,23 @@ This rule raises issues for overloaded binary mathematical and relational operat == Why is this an issue? When overloading binary or relational operators, it is recommended that they be declared hidden friends of the class. -A hidden friend, i.e. a friend function defined in the class body, provides the following benefits: + +=== The hidden friend pattern + +The hidden friend pattern consists of declaring and defining a function directly as a friend inside the class body. This reduces the function's visibility to argument-dependent lookup only. Approximately, such a function is considered only when called on an object of the enclosing class. + +[source,cpp] +---- +struct MyClass { + friend void function(MyClass const& arg) { // This function is a hidden friend of MyClass + ... + } +}; +---- + +=== Benefits of hidden friends + +Using hidden friends provides the following benefits: * in contrast to the member function, it allows conversion to be applied to both operands * in contrast to free functions, it is considered only if one of the operands is an object of the given class