C++结构体复制的相关问题
C语言,C++,这操作内存的语言就是那么的纠结啊,呵呵。我们先定义两个结构体:
struct UMMessage{long mtype;char mtext[100];};struct MsgInfo{sem_t sem;int MQID;struct UMMessage MSG;};假如已经有一个MsgInfo类型的结构体变量Info,现在需要新定义一个MsgInfo类型的结构体,并且等于Info,那么是否我们可以这样:
MsgInfo Info2=Info;
在C++里,这样当然是不行的,我们可以用memcpy函数进行复制,在这个例子中,使用memcpy是没有问题的,但当结构体中定义了std::string的变量时,就容易出错了,因为string在内存上存储是不连续的,不像char,int这些连续存储在内存块上(这个纠结啊)。所以安全起见,当需要复制结构时,自己再添加一个复制函数即可,比如:
void CopyMsgInfo(MsgInfo *dest,MsgInfo *src){dest->MQID=src->MQID;dest->sem=src->sem;CopyUMMessage(&(dest->MSG),&(src->MSG));}void CopyUMMessage(UMMessage *dest,UMMessage *src){memcpy(&(dest->mtext),&(src->mtext),sizeof(dest->mtext));dest->mtype=src->mtype;}数组之间复制也是不能直接用“=”的,再次纠结一下。使用方法如下:
MsgInfo Info2;CopyMsgInfo(&Info2,&Info);
为此,我特意测试了一下C#(基本熟悉),代码如下:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace WindowsFormsApplication1{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { student stu = new student(); stu.x = 1; stu.y = "测试"; student stu2 = stu; MessageBox.Show(stu2.y); } } public struct student { public int x; public string y; }}运行结果:

完全木有问题啊,这C#,这C++,强大的继续强大,傻瓜的继续傻瓜,呵呵。不过对于我们这些从高级语言往下走的人(js,C#,java),只有纠结,没有什么。
注意:结构体不能直接作形参,得用指针,其实也就类似不能直接用“=”。
作者:kunoy出处:http://blog.csdn.net/kunoy申明:作者写博是为了总结经验,和交流学习之用。