1 #include <iostream> 2 #include <string> 3 #include <stdio.h> 4 #include <stdlib.h> 5 using namespace std; 6 7 struct Person 8 { 9 int age; 10 int id; 11 }; 12 13 template <class T> T myRead(void * memory) 14 { 15 char buffer[sizeof(T)]; 16 memcpy(buffer, memory, sizeof(T)); 17 T temp = *((T *)buffer); // 调用 Person 拷贝构造 18 return temp; 19 } 20 21 template <class T> T myRead2(void * memory) 22 { 23 T temp; 24 memcpy(&temp, memory, sizeof(T)); 25 return temp; 26 } 27 28 template <class T> T* myRead3(void * memory, int offset) 29 { 30 T* temp = new T; 31 memcpy(temp, (char*)memory+offset, sizeof(T)); 32 return temp; //返回指针, 有内存泄漏风险 33 } 34 35 template <class T> void myRead4(void * memory, int offset, T* data) 36 { 37 memcpy(data, (char*)memory+offset, sizeof(T)); 38 } 39 40 template <class T> T* myRead5(void * memory, int offset) 41 { 42 T* t = (T*)((char*)memory+offset); 43 return t; 44 } 45 46 47 48 int main() 49 { 50 char bytes[20] = "\x05\x00\x00\x00\x0A\x00\x00\x00\x06\x00\x00\x00\x0C\x00\x00\x00"; 51 Person p = myRead<Person>(bytes); // 调用 Person 拷贝构造 52 printf("age = %d, id = %d\n", p.age, p.id); 53 54 Person p2 = myRead2<Person>(bytes); // 调用 Person 拷贝构造 55 printf("age = %d, id = %d\n", p2.age, p2.id); 56 57 Person* p3 = myRead3<Person>(bytes, 7); 58 printf("age = %d, id = %d\n", p3->age, p3->id); 59 60 Person* p4 = new Person; 61 myRead4<Person>(bytes, 7, p4); 62 printf("age = %d, id = %d\n", p4->age, p4->id); 63 64 //这个会崩溃 65 //Person* p5 = NULL; 66 //myRead4<Person>(bytes, 7, p5); 67 //printf("age = %d, id = %d\n", p5->age, p5->id); 68 69 Person* p6 = myRead5<Person>(bytes, 7); 70 printf("age = %d, id = %d\n", p6->age, p6->id); 71 72 73 74 cin.get(); 75 return 0; 76 }
执行结果
1 age = 5, id = 10 2 age = 5, id = 10 3 age = 1536, id = 3072 4 age = 1536, id = 3072 5 //程序崩溃 6 age = 1536, id = 3072