简体   繁体   English

从DCL60-CPP理解不合规代码示例:遵守一定义规则

[英]Understanding the Noncompliant Code Example from DCL60-CPP: Obey the one-definition rule

I'm looking for some secure coding guideline and came across the SEI CERT C++ Coding Standard. 我正在寻找一些安全的编码准则,并遇到了SEI CERT C ++编码标准。

Most things are clear so far, but I don't understand the last Noncompliant Code Example from DCL60-CPP: Obey the one-definition rule . 到目前为止,大多数事情都很清楚,但是我不了解DCL60-CPP的最后一个不兼容代码示例:遵守一定义规则

In this noncompliant code example, the constant object n has internal linkage but is odr-used within f() , which has external linkage. 在此不兼容的代码示例中,常量对象n具有内部链接,但在具有外部链接的f()使用。 Because f() is declared as an inline function, the definition of f() must be identical in all translation units. 因为f()被声明为内联函数,所以f()的定义在所有转换单元中必须相同。 However, each translation unit has a unique instance of n , resulting in a violation of the ODR. 但是,每个转换单元都有一个唯一的n实例,从而导致违反ODR。

const int n = 42;

int g(const int &lhs, const int &rhs);

inline int f(int k) {
    return g(k, n);
}

I tried to put the shown code in a header file and included it in two separate cpp files. 我试图将显示的代码放在头文件中,并将其包含在两个单独的cpp文件中。 I then compiled it with clang++ and g++. 然后,我用clang ++和g ++对其进行了编译。 Both without warnings. 两者都没有警告。 It executed normally. 它执行正常。

Edit: So what I don't understand is how or under what circumstances the shown Example violates the ODR. 编辑:所以我不明白的是所示示例如何或在何种情况下违反了ODR。

You did violate the ODR. 确实违反了ODR。 Violating the ODR is "undefined behaviour". 违反ODR是“未定义的行为”。

One of the more common forms of undefined behaviour is "doing exactly what the programmer expected". 未定义行为的一种较常见形式是“完全按照程序员的期望来做”。 In my experience though, an even more common form is "doing exactly what the programmer expected nearly all the time, but crashing randomly occassionally". 不过,以我的经验来看,一种更常见的形式是“几乎一直在执行程序员所期望的,但是偶尔会崩溃”。

This particular UB will probably always work - until you switch on improved link-time optimizations, when it may all come crashing down in a heap around your head. 这个特定的UB可能一直可以工作-直到您打开改进的链接时优化功能,否则所有这些可能都会崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM