开发者

Is std::complex stored in an interleaved fashion?

开发者 https://www.devze.com 2023-02-17 05:07 出处:网络
That is, on disk, if I have an array of std::complex, is it stored RIRIRIRI or RRRRIIII or something else?

That is, on disk, if I have an array of std::complex, is it stored RIRIRIRI or RRRRIIII or something else?

My real question is - if I have a structure that I have defined that contains two numbers, c开发者_如何学运维an I do a reinterpret cast an array of my structure to use functions that would expect a std::complex array?

What about memcpy? If both of my structures are floats, that should be ok if they are stored the same?


An array of std::complex defined like so:

std::complex array[COUNT];

...is guaranteed to be stored in memory as RIRIRIRI for the reason that array[i] is by definition the same as i[array], which is to say *(array+i). If the array were stored as RRRRIIII there would be no way to point at an individual array element with a simple pointer.

However there is one case in a typical modern PC where this array IS stored as RRRRIIII: after it is copied to a StructuredBuffer for a GPU in Direct3D 11+. The API call that copies the RIRIRIRI array to the GPU may silently rearrange it as RRRRIIII if this improves GPU performance, which in practice it does.


A C++ class is little more than a struct with some adornments. As such, the members defined in a class are arranged sequentially in memory, contiguously for each element of that type. In other words, an array of std::complex, where each element contains RI, will be stored RIRIRIRI.

You can probably get away with a reinterpret_cast, but you will be depending on the std::complex implementation if you do so -- and that will probably be just fine.


This completely depends on how you stored these in the file in the first place.

You could have done:

ofstream file("somefile.txt");

file << complex_var.real() << "\t" << complex_var.imag() << "\n";

Or

file << complex_var << "\n";

The latter will store it (in text form) as ´(realpart,imaginarypart)`. If writing in binary mode, I wouldn't know, but simply trying and see what output is generated would be an easy (and most likely standardized, in this case) way of seeing what happens.


I'm not sure what the physical meaning of an array of a class on disk is. You shouldn't be just writing the bytes to disk, but using real serialization. Then you know the representation yourself.

As for your other questions, don't do that, even if it appears to work (which it might for now). Just create the std::complex objects from pairs out of your array and process those objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消