cpp:S5827: "auto" should be used to avoid repetition of types

Hello,

Let the following declaration:

const std::string foo = std::string("foo");

The rules says us to use auto to not have type repetition, but there is an alternative:

const std::string foo("foo");

Why do you Sonar proposes only one solution ?
I think this rule should be relabelled: “Avoid repetition of types”

Hello @Oodini,

When we designed this rule, its goal was to promote the use of auto, based on the famous Almost Always Auto article by Herb Sutter, but only focusing on cases which we think at non-controversial (which also explains the title of the rule).

So we considered that:

auto foo = std::string("foo");

Is, without much controversy, better than:

const std::string foo = std::string("foo");

We don’t say that const std::string foo("foo"); is bad (although I personally prefer the auto foo = ... style).

The reason why we propose rewriting it with auto is that this style also works nicely with other cases detected by this rule, while there is no way to avoid repeating the type without using auto for those other cases:

std::string *foo = new std::string{bar};
// =>
auto foo = new std::string{bar};
const std::string foo = static_cast<const std::string>(bar);
// =>
auto foo = static_cast<const std::string>(bar);

We could propose an alternative fix for the cases where it would work, but we did not feel it was worth it because it works nicely with auto.

Hello @JolyLoic,

Once more, thanks for your complete answer.

The problem is you adress two subjects:

  • the wish to avoid repetition ;
  • the wish to favorize auto, in any case.

One could want adress the first point, without the second one. I’ll favorize here the “separation of concerns”.

In the sample code I gave, auto is in no way better than :

const std::string foo("foo");

If I change of type, I’ll have to rewrite anyway my instruction.

Personnally, I dislike/avoid the static initialization with the = sign. :slight_smile:

You could change the rule title to “Avoid repetition of types”, and for the discussed case, suggest auto or the old way to do initialization (without =).

Hello @Oodini,

I created a ticket to apply the changes you suggest.

However, since the rule is not broken in its current state, I can’t promise we’ll work on it in the near future.

1 Like