C++ aliasing rules

前端 未结 2 1494
一整个雨季
一整个雨季 2020-12-05 18:43

Just wondering if someone would confirm a few aliasing rules for me.

I know that aliasing (i.e load-store issues) could cause the following type of code to

相关标签:
2条回答
  • 2020-12-05 18:52

    According to the strict-aliasing rule, you are not allowed to alias the same memory with pointers to different types (except char* and friends), so case 4 could only apply if one of the types was a char*.

    Case 3 though isn't all that different from case 1, as references are implemented as pointers on all compilers I know, though the standard doesn't demand that and an implementation is free to come up with something else.

    0 讨论(0)
  • 2020-12-05 19:08

    It's not specific at all to C++. Consider this C99 bit:

    struct vector {
        double* data;
        size_t n;
    };
    
    void
    plus(struct vector* restrict x, struct vector* restrict y, struct vector* restrict z)
    {
        // same deal as ever
    }
    

    Here, restrict buys us very little: x->data, y->data and z->data are all double* and are allowed to alias. This is exactly like case 1, even when using restrict.

    If there were a restrict keyword in C++ (or when using an extension), the best bet would probably to do plus(vecA.size(), &vecA[0], &vecB[0], &vecB[0]), using the same plus as in case 2. And in fact it's possible to do this right now, using a C89-style interface without restrict but that uses the keyword under the covers.

    0 讨论(0)
提交回复
热议问题