简体   繁体   中英

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 .

Does the following program violate the strict aliasing rule?

Yes, it does. You are dereferencing a double* ( &d ) using a std::int64_t* .

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 . The fact that it is an alias to a double* is not obvious while processing that line.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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