简体   繁体   English

严格别名违规

[英]Strict aliasing violation

Does the following program violate the strict aliasing rule? 以下程序是否违反严格别名规则?

#include <cstdint>

int main()
{
    double d = 0.1;

    //std::int64_t n = *reinterpret_cast<std::int64_t*>(&d); // aliasing violation

    //auto n{*reinterpret_cast<std::int64_t*>(&d)}; // aliasing violation

    auto nptr{reinterpret_cast<std::int64_t*>(&d)};
    auto& n{*nptr};

    ++n;
}

No warning emitted by VS2015, clang or gcc . VS2015, clanggcc没有发出警告。

Does the following program violate the strict aliasing rule? 以下程序是否违反严格别名规则?

Yes, it does. 是的,它确实。 You are dereferencing a double* ( &d ) using a std::int64_t* . 您正在使用std::int64_t*取消引用double*&d )。

The line that violates strict aliasing rule is: 违反严格别名规则的行是:

auto& n{*nptr};

While processing the line, the compilers don't necessarily know how you set the value of nptr . 在处理行时,编译器不一定知道如何设置nptr的值。 The fact that it is an alias to a double* is not obvious while processing that line. 在处理该行时,它是double*的别名这一事实并不明显。

Yes, this violates strict aliasing. 是的,这违反了严格的别名。 You are accessing an object d of type double , though a pointer nptr which is not a pointer to double or any type related to it. 您正在访问double类型的对象d ,但是指针nptr不是指向double的指针或与之相关的任何类型。

Just because a compiler does not emit a warning does not mean it isn't a violation. 仅仅因为编译器没有发出警告并不意味着它不是违规。 Violations of strict arising are UB (since they're a matter of runtime behavior) and therefore do not require a diagnostic. 违反严格的行为是UB(因为它们是运行时行为的问题),因此不需要诊断。

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

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