| Issue |
52837
|
| Summary |
cppcoreguidelines-prefer-member-initializer: bad fix-it with for initializer depending on other statements
|
| Labels |
clang-tidy
|
| Assignees |
|
| Reporter |
sfc-gh-sgiesecke
|
cppcoreguidelines-prefer-member-initializer suggests a bad fix-it for the following code:
```
#include <string>
struct Foo {
Foo(int n) {
m_str.append(std::to_string(n));
m_bar = m_str.length();
}
std::string m_str;
int m_bar;
};
```
If the fix-it were applied, this resulted in:
```
#include <string>
struct Foo {
Foo(int n) : m_bar(m_str.length()) {
m_str.append(std::to_string(n));
}
std::string m_str;
int m_bar;
};
```
This changes behaviour, since the initializer for `m_bar` depends on the statement that modifies `m_str`. Now, `m_bar` will be initialized to 0, instead of the length of `m_str` after the call to `append`.
This is pretty dangerous behaviour, as the change is syntactically correct.
Probably, it doesn't make sense to warn here (by default), since a proper fix may require significant refactoring. In this particular case, of course, we could do:
```
#include <string>
struct Foo {
Foo(int n) : m_str(std::to_string(n)), m_bar(m_str.length()) {}
std::string m_str;
int m_bar;
};
```
However, it doesn't seem that the rule could determine in general if such a transformation is possible.
See https://godbolt.org/z/qvoWv5xbr
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs