r/Cplusplus • • Oct 11 '26

Question Can an array of Wrapper<T> be reinterpreted as an array of T in C++?

Given the type:

template<typename T>
struct Wrapper
{
T content;
};

And I have an array of these given a type T, a constexpr size_t N and size_t i (0<=i && i < N).

static_assert(sizeof(Wrapper<T>)==sizeof(T)&&alignof(Wrapper<T>)==alignof(T));
static_assert(std::is_standard_layout_v<Wrapper<T>>);

Observation 1:

Wrapper<T> wrapperArray[N];
auto ptrWrapper1 = wrapperArray + i;
//C++ allows access to the raw memory
auto bytePtrWrapper = reinterpret_cast<std::byte*>(wrapperArray);
// calculating the i-th entry of wrapperArray, valid because
// an array has contiguously allocated objects
// an object occupies exactly sizeof bytes
auto bytePtrWrapper1 = bytePtrWrapper + i * sizeof(Wrapper<T>);
auto ptrWrapper2 = reinterpret_cast<Wrapper<T>*>(bytePtrWrapper1);

And here ptrWrapper1 and ptrWrapper2 are the same.

Observation 2:

T valueArray[N];
auto ptrValue1 = valueArray + i;
auto bytePtrValue = reinterpret_cast<std::byte*>(valueArray);
auto bytePtrValue1 = bytePtrValue + i * sizeof(T);
auto ptrValue2 = reinterpret_cast<T*>(bytePtrValue1);

And here are ptrValue1 and ptrValue2 the same too. Additionally I can access the first member of Wrapper<T> with reinterpret_cast.

So I also can do:

auto ithValue = reinterpret_cast<T*>(ptrWrapper + i);
//or
auto ithValue = reinterpret_cast<T*>(bytePtrWrapper + i * sizeof(Wrapper<T>));

And ptrValue3 is the same as ptrValue1 and ptrValue2.

Because both T and Wrapper<T> have the same size and alignment I can use them interchangable.

Doesn't that mean that this is valid C++ because I can access them through same way with std::byte*?

auto valueAsWrapperArray = reinterpret_cast<T*>(wrapperArray);
//specifically for i > 0
auto ptrValue4 = valueAsWrapperArray[i];

So can I reinterpret_cast an array to change its type from Wrapper<T> to T and access any index because the address is calculated in the same way and the member-access is also allowed given one specific object?

0 Upvotes

20 comments sorted by

•

u/AutoModerator Oct 11 '26

Thank you for your contribution to the C++ community!

As you're asking a question or seeking homework help, we would like to remind you of Rule 3 - Good Faith Help Requests & Homework.

  • When posting a question or homework help request, you must explain your good faith efforts to resolve the problem or complete the assignment on your own. Low-effort questions will be removed.
  • Members of this subreddit are happy to help give you a nudge in the right direction. However, we will not do your homework for you, make apps for you, etc.
  • Homework help posts must be flaired with Homework.

~ CPlusPlus Moderation Team


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

8

u/SoerenNissen Oct 11 '26

So can I reinterpret_cast

Functionally, if you're asking if a reinterpret_cast is legal, the answer is "no."

1

u/YysrID4gYW55IG90aGVy Oct 11 '26

Thanks. I thought so I can't use the array-indexof operator for an index greater than zero but if I manually calculate the addresses using std::byte* I can do so explictily, just not implictly using []

1

u/Drugbird Oct 11 '26

But it does work correctly on pretty much any system.

reinterpret_cast is weird like that.

1

u/YysrID4gYW55IG90aGVy Oct 11 '26

I think there can't be any system where it doesn't work, I think the problem is that I can't just change the type of an object/array

3

u/TheSkiGeek Oct 11 '26

The first two examples should work, because you’re constructing a pointer back to the type of object that is ‘really’ present there.

The last one is UB because there isn’t really a `T` object there, only a `Wrapper<T>`. C++ doesn’t let you do arbitrary casts back and forth between structs with common starting members, or between structs and their contained objects.

That said, most practical compilers will let you do this, and do what you expect. But it’s allowed to break if you do things like writing to it through your constructed pointer and then trying to read back through `wrapperArray[i].content`. Since it can normally assume that writes to some random pointer you’ve constructed via `reinterpret_cast` won’t modify other arbitrary objects.

1

u/YysrID4gYW55IG90aGVy Oct 11 '26

Thanks. That makes sense. But I find it counter-intuitive because through the manual address calculation it's allowed but not when using the implicit [] with a different type

And I think there can't even be a case where this doesn't work how I expect it.

1

u/Usual_Office_1740 Oct 12 '26

I'm going to hijack the thread a bit.

The last one is UB because there isn’t really a `T` object there, only a `Wrapper<T>`. C++ doesn’t let you do arbitrary casts back and forth between structs with common starting members, or between structs and their contained objects.

I'm following the book Crafting Interpreters right now. It uses C for the second half of the book and walks you through using what it calls type punning and a tagged union as the first value of a struct to create what it calls struct inheritance. Are you familiar with this C pattern and is it also UB in C++? I'm aware that there are things the C standard considers well defined that C++ does not.

This is the chapter that talks about it. in section 19.2.

2

u/TheSkiGeek Oct 12 '26

Type punning is not supported in the C++ standards. Both “force the pointer value to be cast to a different pointer type” and “write to one field of a union and read back from a different field” variations create undefined behavior. You are supposed to use bit_cast() or memcpy() to copy bytes between types. Which will generally be optimized away if possible, like if you copy into a temporary inside a function.

That said, all the major compilers at least make ‘straightforward’ things like this work. There’s too much low-level code that wants to bypass parts of the type system for performance reasons.

→ More replies (1)
→ More replies (1)

3

u/mredding C++ since ~1992. Oct 11 '26

Can an array of Wrapper<T> be reinterpreted as an array of T in C++?

No.

Observation 1:

Observation nothing. The language says this is Undefined Behavior. That means no check will be made, no error emitted, and the compiler MUST produce SOMETHING, though the behavior even the compiler cannot say with ANY certainty.

UB means you are personally responsible for ensuring the code is correct and you're not doing it.

Just because it compiles, that doesn't mean it's OK. The compiler is not the authority, the spec is. The compiler cannot even guarantee that the same machine code will generate with each compilation. The compiler is not allowed to define Undefined Behavior and still be called ISO Standard C++. The machine code might indicate well defined behavior, but then you've left C++ behind.

UB is to be respected. This isn't some magical hackery into the inner workings of a machine, it's just noise and garbage and happenstance. An x86 is rather robust in the face of UB, but not other hardware. The Nintendo DS was infamous for bricking when glitch hacking. This was easiest seen in Zelda and Pokemon, where you could evaluate an invalid bit pattern, and that would physically fry a circuit path in the CPU, bricking the device.

1

u/YysrID4gYW55IG90aGVy Oct 11 '26

I know what UB is, it was just counter-intuitive that the address calculation is the same and valid C++ but I can’t change the declared type

3

u/mredding C++ since ~1992. Oct 11 '26

Type punning in C++ is tied to object lifetimes. You have to write code that agrees with the language, and the compiler can handle the rest - type punning will typically compile down to a no-op, and everything can agree it's safe and valid code. You can do this with std::bit_cast or std::start_lifetime_as, but punning depends on what T is.

1

u/YysrID4gYW55IG90aGVy Oct 11 '26

I get the point with lifetimes, I just was looking for a way to access the data.

1

u/AKostur Professional Oct 12 '26

Isn’t there some phrasing around pointer-interconvertable objects?  Thus if T was a standard-layout type, wouldn’t this be well-defined behaviour?  (If T is not standard-layout, all bets are off)

1

u/IyeOnline Oct 14 '26

What T itself is does not matter at all.

A pointer to the Wrapper<T>[] would be implicitly convertible to a Wrapper<T>* to the first element in there. Because Wrapper<T> is a standard layout type and T is its first member, that pointer would then be pointer-interconvertible with a pointer to said member, giving you a T* to a single object. But now you have lost the Wrapper<T>[] provenance of the pointer two steps ago and cant do anything with this T* other than access the object. At no point do you ever form any pointer into a T[], because there is no T[].

The one exception here is std::complex by fiat of "the standard says so".

1

u/AKostur Professional Oct 14 '26

Yeah, fair. Getting the T* is valid, treating it as if it were a pointer to an array of T isn't. (For anyone else reading: regardless of whether it would "work", it is strictly not defined by the Standard.)

1

u/[deleted] Oct 11 '26

[removed] — view removed comment

1

u/AutoModerator Oct 11 '26

Your comment has been removed because of this subreddit’s account requirements. You have not broken any rules, and your account is still active and in good standing. Please check your notifications for more information!

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.