Die std :: memcpy () Funktion < /h4>
Für historische (und c -Kompatibilität). Eine
falsche Verwendung von std :: memcpy () für den Typ Punning wäre wie folgt: < /p>
Code: Select all
// suppose this holds for this example
static_assert(sizeof(int) == sizeof(float));
#include
#include
#include
int main() {
float f = 1.5f;
void *p = malloc(sizeof f);
assert(p);
int *q = std::memcpy(p, &f, sizeof f);
int value = *q; // UB
//
}
< /code>
Der Grund, warum dies illegal ist, besteht darin, dass der Aufruf an std :: memcpy ()
ein Float -Objekt in den Speicher kopiert, auf das P durch P, effektiv
die Lebensdauer eines Float -Objekts in diesem Speicher startet. Da q ein
int*ist, ist dasferencing es ub. Nicht malloc ()