Is casting std::pair const& to std::pair const& safe?

It’s NOT portable to do so. std::pair requirements are laid out in clause 20.3. Clause 17.5.2.3 clarifies that Clauses 18 through 30 and Annex D do not specify the representation of classes, and intentionally omit specification of class members. An implementation may define static or non-static class members, or both, as needed to implement the … Read more

Why doesn’t this reinterpret_cast compile?

In C++ reinterpret_cast can only perform a specific set of conversions, explicitly listed in the language specification. In short, reinterpret_cast can only perform pointer-to-pointer conversions and reference-to-reference conversions (plus pointer-to-integer and integer-to-pointer conversions). This is consistent with the intent expressed in the very name of the cast: it is intended to be used for pointer/reference … Read more

Is reinterpret_cast type punning actually undefined behavior?

I believe your misunderstanding lies here: This reads to me as an explicit statement that the result of reinterpret_cast<T&>(v) is an lvalue reference to an object of type T, to which access is clearly “through a glvalue of” “the dynamic type of the object”. [basic.lval]/8 is a bit misleading because it talks about the dynamic … Read more

Does accessing the first field of a struct via a C cast violate strict aliasing?

First, it is legal to cast in C. §6.7.2.1/13: Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, … Read more

Is there a (semantic) difference between the return value of placement new and the casted value of its operand?

Only a can safely be used to directly access the Foo object created by the placement new-expression (which we’ll call x for ease of reference). Using b requires std::launder. The value of a is specified in [expr.new]/1: If the entity is a non-array object, the result of the new-expression is a pointer to the object … Read more

Should I use static_cast or reinterpret_cast when casting a void* to whatever

Use static_cast: it is the narrowest cast that exactly describes what conversion is made here. There’s a misconception that using reinterpret_cast would be a better match because it means “completely ignore type safety and just cast from A to B”. However, this doesn’t actually describe the effect of a reinterpret_cast. Rather, reinterpret_cast has a number of … Read more

When to use reinterpret_cast?

The C++ standard guarantees the following: static_casting a pointer to and from void* preserves the address. That is, in the following, a, b and c all point to the same address: int* a = new int(); void* b = static_cast<void*>(a); int* c = static_cast<int*>(b); reinterpret_cast only guarantees that if you cast a pointer to a … Read more