[英]cppcheck: one definition rule is violated when overriding
In the following code (which is a minimal example based on a much more complex code), a base class defines a struct local to the class.在以下代码中(这是基于更复杂代码的最小示例),基本 class 定义了 class 的本地结构。 A derived class overrides this definition, but uses also the definition in the base class.派生的 class 会覆盖此定义,但也使用基础 class 中的定义。
#include <iostream>
struct base {
struct update;
void apply(int& x);
};
struct base::update {
void operator()(int& x)
{
++x;
}
};
void base::apply(int& x) { update{}(x); }
struct deriv : public base {
struct update;
void apply(int& x, int& y);
};
struct deriv::update {
void operator()(int& x, int& y)
{
typename base::update{}.operator()(x);
++y;
}
};
void deriv::apply(int& x, int& y) { update{}(x, y); }
int main()
{
base b;
int x = 1;
b.apply(x);
std::cout << x << std::endl;
int y = 2;
deriv d;
d.apply(x, y);
std::cout << x << ' ' << y << std::endl;
return 0;
}
Compiling with gcc and -Wall -Wextra
does not issue any warning.使用 gcc 和-Wall -Wextra
编译不会发出任何警告。 The output of the code is as expected代码的 output 符合预期
2
3 3
However, when analyzing the code with cppcheck, with --enable=all
, I get the following:但是,当使用 cppcheck 和--enable=all
分析代码时,我得到以下信息:
Checking test.cpp ...
test.cpp:25:24: style: Parameter 'x' can be declared with const [constParameter]
void operator()(int& x, int& y)
^
test.cpp:9:1: error: The one definition rule is violated, different classes/structs have the same name 'update' [ctuOneDefinitionRuleViolation]
struct base::update {
^
test.cpp:24:1: note: The one definition rule is violated, different classes/structs have the same name 'update'
struct deriv::update {
^
test.cpp:9:1: note: The one definition rule is violated, different classes/structs have the same name 'update'
struct base::update {
The first reported error ( Parameter 'x' can be declared with const
) seems clearly a false positive, as clearly I need non-const reference to be able to modify it, and in fact the code obviously does not compile with a const int&
.第一个报告的错误( Parameter 'x' can be declared with const
)显然是误报,因为很明显我需要非常量引用才能修改它,实际上代码显然不能用const int&
编译。
But what about the second error on ODR violation?但是关于 ODR 违规的第二个错误呢? Is this a correct diagnose, and if so why cannot I override the definition of update
?这是一个正确的诊断,如果是这样,为什么我不能覆盖update
的定义?
It is also a false positive.这也是一个误报。 There is nothing wrong with declaring a nested class of the same name in the derived class.在派生的 class 中声明同名的嵌套 class 并没有错。 The two nested classes will be separate entities and each can have one definition per one-definition-rule.这两个嵌套的类将是单独的实体,并且每个类都可以根据一个定义规则有一个定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.