Intel® oneAPI DPC++/C++ Compiler
Talk to fellow users of Intel® oneAPI DPC++/C++ Compiler and companion tools like Intel® oneAPI DPC++ Library, Intel® DPC++ Compatibility Tool, and Intel® Distribution for GDB*
801 Discussions

Incorrect optimization: std::byte representation swap not observed

Mingxin_Wang
Beginner
380 Views

A trivially copyable object (struct Foo) is stored inside a std::byte buffer via placement new. Swapping two such objects by swapping their std::byte arrays (std::swap on the arrays) should exchange their object representations. The program prints the original value instead of the swapped value only with icx; other compilers (GCC, Clang, MSVC, NVHPC) produce the expected output. This suggests icx fails to treat writes through std::byte as potentially modifying the overlapped object, violating the aliasing rules that grant std::byte access to any object's representation.

Compiler Explorer link

#include <cstddef> /* For std::byte */
#include <cstdio> /* For printf */
#include <memory> /* For std::construct_at */
#include <new> /* For std::launder */
#include <type_traits> /* For std::is_trivially_copyable_v */
#include <utility> /* For std::swap */

struct Erased {
  template <class T>
  Erased(T val) requires(std::is_trivially_copyable_v<T> &&
      sizeof(T) <= sizeof(void*) && alignof(T) <= alignof(void*)) {
    std::construct_at(reinterpret_cast<T*>(data), val);
  }

  void Swap(Erased& rhs) {
    std::swap(data, rhs.data);
    std::swap(padding, rhs.padding);
  }

  alignas(alignof(void*)) std::byte data[sizeof(void*)];
  void* padding = nullptr;
};

int main() {
  struct Foo {
    const char* msg;
  };
  Erased a{Foo{"bug"}};
  Erased b{Foo{"ok"}};
  a.Swap(b);
  Foo* p = std::launder(reinterpret_cast<Foo*>(a.data));
  puts(p->msg); // Expect: "ok"; Actual: "bug"
}

Expected Result: Program outputs: ok

Actual Result: Program outputs: bug

Impact: Causes silent logic errors in type‑erasure / small buffer optimization code that relies on valid object representation swaps.

0 Kudos
0 Replies
Reply