0

The rules of strict aliasing are mystifying (to me). Is the following code legal or UB?

Assume the buffer comes from a socket, and an Alias type wasn't placement-new'ed anywhere within my code.

struct Alias
{
  int64_t a;
  int64_t b;
}

int read(const QByteArray& buffer)
{
  Alias* alias = reinterpret_cast<Alias*>(buffer.data());
  int isThisUB = alias.a;
  return isThisUB;
}

I'm not sure if this is UB or not because buffer.data() returns a char*? If it is, does launder'ing it make it well defined?

int read(const QByteArray& buffer)
{
  Alias* alias = std::launder(reinterpret_cast<Alias*>(buffer.data()));
  int isThisUB = alias.a;
  return isThisUB;
}

Do I actually need to use memcpy or some union here?


Reasons I'm confused:

Nicolas Holthaus
  • 7,763
  • 4
  • 42
  • 97
  • `function` isn't a keyword in C++ – Aykhan Hagverdili Oct 09 '20 at 15:49
  • @AyxanHaqverdili the first part yes. I'm guessing this isn't what `std::launder` is designed to solve? – Nicolas Holthaus Oct 09 '20 at 15:50
  • @NicolasHolthaus: For whatever reason, compiler writers seem opposed to having a "launder" construct with a broad meaning on the basis that it would impede optimization, willfully ignoring the fact that such a construct would make it easy to do things that are otherwise difficult, and that in many such cases, the performance of code with optimization blocked wouldn't be much different from the performance of the most efficient possible code *that would actually accomplish the required task*. It may be much slower than the useless broken machine code... – supercat Oct 10 '20 at 18:58
  • ...that could have been produced without the barrier, but the ability to generate machine code to quickly perform some action that doesn't meet application requirements isn't very useful. – supercat Oct 10 '20 at 19:01

0 Answers0