Issue 135508
Summary [clang-tidy] Check request: bugprone-union-inactive-member-access
Labels clang-tidy
Assignees
Reporter denzor200
    
Needs a check that will find a reading of a union's field which was executed after another field has been written which remains active.

EXAMPLE:
```
union SimpleUnion {
    int x;
    double y;
};

void process() {
 SimpleUnion u;

    u.x = 10;
    std::cout << "x = " << u.x << std::endl; // OK

    u.y = 3.14;
    std::cout << "y = " << u.x << std::endl; // BAD - looks like a typo, are you meaning `std::cout << "y = " << u.y`??
}
```

In the case when the union's trick used for obtaining a value of another type by reinterpreting the representation of an object, the check will suggest to use `std::memcpy` or even `std::bit_cast` if it's available. The efficiency would remain the same - compilers know how to optimize both of them.

BEFORE:
```
template<typename T>
T perform_type_punning(std::ptrdiff_t offset)
{
    union {
        T memptr;
        std::ptrdiff_t offset_;
    };
    offset_ = offset;
 return memptr;
}
```

AFTER:
```
template<typename T>
T perform_type_punning(std::ptrdiff_t offset)
{
    T memptr;
 std::memcpy(&memptr, &offset, sizeof(offset));
    return memptr;
}
```

AFTER(C++20):
```
template<typename T>
T perform_type_punning(std::ptrdiff_t offset)
{
    return std::bit_cast<T>(offset);
}
```

_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to