Skip to content

False positives in modernize-use-default-member-init in clang-tidy 21 #156295

@arvid-norlander

Description

@arvid-norlander

The release notes for clang-tidy 21 reads:

Improved modernize-use-default-member-init check by matching arithmetic operations, constexpr and static values, and detecting explicit casting of built-in types within member list initialization.

However there seem to be some false positives when there is an expression that partly depends on a constructor argument. E.g.:

#include <cstdint>

constexpr double CONSTANT = 2.0;

class Example1
{
   explicit Example1(const int32_t param)
   : member(
        static_cast<int32_t>(CONSTANT / (static_cast<double>(param) * 0.001)))
   {
   }

   const int32_t member;
};

This results in:

test.cpp:13:18: error: use default member initializer for 'member' [modernize-use-default-member-init,-warnings-as-errors]
    8 |    : member(
      |      ~~~~~~~
    9 |         static_cast<int32_t>(CONSTANT / (static_cast<double>(param) * 0.001)))
      |         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   10 |    {
   11 |    }
   12 | 
   13 |    const int32_t member;
      |                  ^     

Using -fix creates the invalid code below:

#include <cstdint>

constexpr double CONSTANT = 2.0;

class Example1
{
   explicit Example1(const int32_t param)
    
   {
   }

   const int32_t member{
        static_cast<int32_t>(CONSTANT / (static_cast<double>(param) * 0.001))};
};

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions