Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::tuple and memcpy

Tags:

c++

stdtuple

I am aware that the standard declares that std::tuple is not trivially copiable so std::memcpy will have an undefined behavior on this type, but are there infos (maybe something compiler specific) to safely memcpy std::tuple with basic types (int, float)?

A possible example:

auto my_computation = [](...){ something...; return std::make_tuple(...) }

auto ret = my_computation(...);

unsigned char buf[...];
memcpy(buf, &ret, sizoof(ret));

//send the bytes out to another device

I have had no issues (for now) with this raw memcpy but I am not sure if it is reliable (g++ (Alpine 10.3.1_git20210424) 10.3.1 20210424).

I can assure that the receiver architecture is compatible with this bytes representation (e.g. endianess) so this is not a problem.

like image 716
kaixi Avatar asked Feb 22 '26 02:02

kaixi


1 Answers

Tuple memory representation is implementation defined, just like the order of derived class object and base class object. If your data blocks are large and individual copy creates performance issues (which is a rare and niche problem), you should create own structures with standard memory layout. This also would allow implementation of byte order change.

like image 64
Swift - Friday Pie Avatar answered Feb 23 '26 16:02

Swift - Friday Pie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!