Skip to content

False positives in modernize-use-default-member-init in clang-tidy 21 when constant is in cpp file and class in a header #156412

@arvid-norlander

Description

@arvid-norlander

Another false positive (but distinct from #156295):

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.

If you have:

test.h:

#include <cstdint>

class Example1
{
   explicit Example1(int32_t param);

   int32_t member;
};

test.cpp:

#include "test.h"

namespace {
constexpr double CONSTANT = 2.0;
}

Example1::Example1()
: member(CONSTANT)
{
}

clang-tidy-21 will incorrectly report:

/home/tmgarn/workspace/reproducer/test.h:7:12: error: use default member initializer for 'member' [modernize-use-default-member-init,-warnings-as-errors]
    7 |    int32_t member;
      |            ^     
      |                  {CONSTANT}
1 warning treated as error

If you use -fix, it will incorrectly apply this change, but since the constant is defined in the cpp file, the code will not build. Many times you would not want to move the constant to the header, so this should at least be a configurable part of the check.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions