Falsely accused of a C-Style Cast? [std::vector ctor with initializer_list]

The following code is triggering these two rules:

cpp:S871 C-style and functional notation casts should not be used
cpp:S5303: C-style casts (other than void casts) and functional notation casts (other than explicit constructor calls) shall not be used

class Test
    Test() {}
    explicit Test(const std::vector<int>& dims) : m_dims(dims) {}

    std::vector<int> m_dims;

Test tt;
tt = Test({2, 2});

Changing the last line to the explicit tt = Test(std::vector<int>{2, 2}) resolves the issue - i.e. the code is no longer flagged.

I fail to see how this is in any way a C-Style cast or a functional cast. I understand this implicit syntax can be considered ‘undesirable’ in some codebases, but it should be a separate rule.
Is the implicit cast to a std::initializer_list the problem?

SonarQube server 8.9.0, SonarScanner, sonar.cfamily

Hello @Sidelobe,

In the expression Test({2, 2}), there are several operations:

  • An initializer_list is created for {2, 2}
  • This list is used to initialize a vector<int>
  • This vector is converted to a Test through a function cast (that is also an explicit constructor call)

This is this conversion that is reported.

However, in both rules, the intent was not to report an explicit constructor call. We correctly detect this situation when you explicitly set the type, but not when it’s omitted. I created a ticket to correct this false positive.

Thank you for reporting it to us!


Hello Loïc

Thanks for the explanations and for opening the ticket! I’m happy to contribute :slight_smile: