Subject: c++14 .. c++20 reading byte-sized buffers via magical char/byte. When need to memcpy()?
From: Roman Babinicz (rb_at_[hidden])
Date: 2020-08-03 08:49:56
If I understand correct then in C++14 to read memory of object like e.g.
float (it is required that the type is trivially-copyable) you should:
copy it with std::memcpy, then read it
through unsigned char * (or reference)?
Reading through just "char*" (or reference) is also permitted. Unsigned
char is not.
This rule results from standard about glvalue, copying memory to
array and then reading the array.
Is this correct?
In c++17 stype std::byte joins the two magical types that can be used to
For some types, the memcpy() operation is not required, right?
If the object to read was actually allocated as new char then you can
read it by dereferencing char*.
You can read it also by dereferencing unsigned char* and std::byte*
right? As in following example:
auto buf = new unsigned char;
std::byte * p1 = reinterpret_cast<std::byte*>(buf);
*(p1+3) = std::byte(42);
char * p2 = reinterpret_cast<char*>(buf);
*(p2+3) = 42;
So the types of the pointers used to access (like p1 here)
can be unsigned char, char, std::byte(since c++17).
What are the allowed types for the buffer allocation new .... for
this to work?
I assume unsigned char, char, signed char, std::byte.
What about enum class that uses one of this 3 as underlying type?
What about other fundamental 1-byte types, e.g. integral types?
Is this valid for all 1-byte tirivialy-copyable objects?
How it is for C++14, and what changed in C++17 and C++20 about this?
 http://eel.is/c++draft/basic.lval#11.3 - we must read as "a char,
unsigned char, or stdâ::âbyte type" (but not as signed char!); C++14
 http://eel.is/c++draft/expr.add#4 - to access i-th element of array;
see http://eel.is/c++draft/dcl.array for what is an array
 http://eel.is/c++draft/basic.types#2 - we can read any
trivially-copyable type T after we std::memcpy it
STD-DISCUSSION list run by firstname.lastname@example.org
Older Archives on Google Groups