có nha, nó là undefined behavior =] C style cast (A*)
kiểu đó ở đây tương đương với reinterpret_cast
, mà reinterpret_cast
chỉ cast được object thành (unsigned) char*
thôi, chiều ngược lại chỉ đúng khi (u)char*
đó được cast từ A
nào đó :V
vd ở cái video này nói thẳng UB nè :V https://www.youtube.com/watch?v=o3j6hfXDCVc
https://en.cppreference.com/w/cpp/language/reinterpret_cast nói muốn cast từ A*
thành B*
- Any object pointer type
T1*
can be converted to another object pointer typecv T2*
. This is exactly equivalent to static_cast<cv T2*>(static_cast<cv void*>(expression)) (which implies that ifT2
's alignment requirement is not stricter thanT1
's, the value of the pointer does not change and conversion of the resulting pointer back to its original type yields the original value). In any case, the resulting pointer may only be dereferenced safely if allowed by the type aliasing rules (see below)
thì phải tuân theo type aliasing :V
Whenever an attempt is made to read or modify the stored value of an object of type
DynamicType
through a glvalue of typeAliasedType
, the behavior is undefined unless one of the following is true:
AliasedType
andDynamicType
are similar .AliasedType
is the (possibly cv-qualified) signed or unsigned variant ofDynamicType
.AliasedType
is std::byte, (since C++17)char, or unsigned char: this permits examination of the object representation of any object as an array of bytes.
nghĩa là chỉ đúng từ chiều T*
sang (u)char*
thôi :V chiều ngược lại chỉ đúng khi (u)char*
đó là con trỏ được cast từ T*
trước đó:
- A pointer to member object of some class
T1
can be converted to a pointer to another member object of another classT2
. IfT2
's alignment is not stricter thanT1
's, conversion back to the original typeT1
yields the original value, otherwise the resulting pointer cannot be used safely.
cách làm đúng phải là memcpy
đống bytes đó vào A a;
hoặc khi read mấy bytes đó read 4/8 byte length trước, lặp vòng for length-- rồi tạo A a;
và read thẳng vào (byte*)&a
(cũng là 1 kiểu của memcpy :V)
hoặc bảo đảm alignment của receivedData
đúng với alignment của A
(hơi khó vì có thêm 4 bytes length ở đằng trước, nhưng nếu alignof(A) < 4 thì dễ), rồi gọi placement new cho từng object a
trong mảng length
object A đó :V