When used as a type specifier in a declaration, auto
allows the compiler to deduce the type of a variable based on the type of the
initialization expression.
When the spelling of the initialization expression already contains the type of the declared variable, it leaves no ambiguity and auto
should be used as it makes the code easier to read and reduces duplication. This includes:
- Initializations using
new
void f() {
LongAndBoringClassName *avoid = new LongAndBoringClassName(); // Noncompliant
auto prefer = new LongAndBoringClassName(); // Compliant
}
- Template factory functions for smart pointers
void f() {
std::unique_ptr<LongAndBoringClassName> avoid = std::make_unique<LongAndBoringClassName>(); // Noncompliant
auto prefer = std::make_unique<LongAndBoringClassName>(); // Compliant
}
void f() {
C *c = new LongAndBoringClassName(); // Compliant
LongAndBoringClassName *avoid = static_cast<LongAndBoringClassName*>(c); // Noncompliant
auto prefer = static_cast<LongAndBoringClassName*>(c); // Compliant
}
The rule S6234 detects other situations where auto
can improve readability.