Is std::memcpy between different trivially copyable types undefined behavior?

The standard may fail to say properly that this is allowed, but it’s almost certainly supposed to be, and to the best of my knowledge, all implementations will treat this as defined behaviour. In order to facilitate the copying into an actual char[N] object, the bytes making up the f object can be accessed as … Read more

gcc, strict-aliasing, and horror stories [closed]

No horror story of my own, but here are some quotes from Linus Torvalds (sorry if these are already in one of the linked references in the question): http://lkml.org/lkml/2003/2/26/158: Date Wed, 26 Feb 2003 09:22:15 -0800 Subject Re: Invalid compilation without -fno-strict-aliasing From Jean Tourrilhes <> On Wed, Feb 26, 2003 at 04:38:10PM +0100, Horst … Read more

Why can’t the C compiler optimize changing the value of a const pointer assuming that two pointers to the same variable would be illegal/UB?

Why can’t the C Compiler optimize the first line away, under the assumption, that two pointers to the same variable would be illegal/UB? Because you haven’t instructed the C compiler to do so — that it is allowed to make that assumption. C has a type qualifier for exactly this called restrict which roughly means: … Read more

reinterpret_cast between char* and std::uint8_t* – safe?

Ok, let’s get truly pedantic. After reading this, this and this, I’m pretty confident that I understand the intention behind both Standards. So, doing reinterpret_cast from std::uint8_t* to char* and then dereferencing the resulting pointer is safe and portable and is explicitly permitted by [basic.lval]. However, doing reinterpret_cast from char* to std::uint8_t* and then dereferencing … Read more

In C++, should I bother to cache variables, or let the compiler do the optimization? (Aliasing)

At first glance, I thought the compiler could generate equivalent assembly for both versions with optimization flags activated. When I checked it, I was surprised to see the result: Source unoptimized.cpp note: this code is not meant to be executed. struct bitmap_t { long long width; } bitmap; int main(int argc, char** argv) { for … Read more

Using this pointer causes strange deoptimization in hot loop

Pointer aliasing seems to be the problem, ironically between this and this->target. The compiler is taking into account the rather obscene possibility that you initialized: this->target = &this In that case, writing to this->target[0] would alter the contents of this (and thus, this->target). The memory aliasing problem is not restricted to the above. In principle, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)