rspec/rules/S6005/cfamily/rule.adoc
Fred Tingaud 22b4470f2a
Modify CFamily rules: CPP-4080 Refresh and standardize CppCoreGuidelines references (#3514)
Update all links to C++ Core Guidelines to `e49158a`.

Refresh done using the following script and some manual edits:
db76e34e74/personal/fred-tingaud/rspec/refresh-cppcoreguidelines.py

When re-using this script, be mindful that:
 - it does not cover `shared_content`
 - it does not properly escape inline code in links (e.g., "[=]" or "`mutex`es")
 - it does not change `C++` to `{cpp}` in link titles.

Co-authored-by: Marco Borgeaud <marco.borgeaud@sonarsource.com>
2023-12-20 10:08:18 +01:00

67 lines
2.0 KiB
Plaintext

== Why is this an issue?
{cpp}17 introduced structured binding, a syntax that initializes multiple entities by elements or members of an object. It is handy to emulate several return values from a function.
Suppose you have a function that returns a pair:
[source,cpp]
----
std::pair<std::string, std::string> getPair();
----
Structured binding allows you to bind the members of the ``++std::pair++`` class directly to new names:
[source,cpp]
----
auto [firstName, lastName] = getPair();
----
The names ``++firstName++`` and ``++lastName++`` are called structured bindings. As you can see, structured binding makes the code more readable as it allows binding values to names that carry information about their purpose.
Structured binding works with:
* Raw arrays, by binding a name to each element
* Any type that has a tuple-like API
* Classes and structures where all non-static data members are publicly accessible
This rule will detect places where ``++std::pair++`` and ``++std::tuple++`` can be effortlessly replaced by a structured binding.
=== Noncompliant code example
[source,cpp,diff-id=1,diff-type=noncompliant]
----
void printingMap(const std::map<int, std::string>& map) {
for (const auto& elem : map) { // Noncompliant
std::cout << elem.first << ": " << elem.second << "\n";
}
}
----
=== Compliant solution
[source,cpp,diff-id=1,diff-type=compliant]
----
void printingMap(const std::map<int, std::string>& map) {
for (const auto& [key, value] : map) { // Compliant
std::cout << key << ": " << value << "\n";
}
}
----
== Resources
=== Documentation
* {cpp} reference - https://en.cppreference.com/w/cpp/language/structured_binding[Structured binding declaration]
=== External coding guidelines
* {cpp} Core Guidelines - https://github.com/isocpp/CppCoreGuidelines/blob/e49158a/CppCoreGuidelines.md#f21-to-return-multiple-out-values-prefer-returning-a-struct-or-tuple[F.21: To return multiple "out" values, prefer returning a struct or tuple]