我有这个结构:
using SPECIAL_EVENT_S = struct tagSpecialEvent
{
COleDateTime datEvent;
CString strEvent;
CString strLocation;
int iSRREventType;
int iSMREventType;
int iForeignLanguageGroupMenuID;
COleDateTime datEventStartTime;
COleDateTime datEventFinishTime;
BOOL bEventAllDay;
BOOL bSetReminder;
int iReminderUnitType;
int iReminderInterval;
int iImageWidthPercent;
CString strImagePath;
CString strTextBeforeImage;
CString strTextAfterImage;
CChristianLifeMinistryDefines::VideoConferenceEventType eType;
};
我有这个结构的实例作为CListBox
项中的指针。我现在需要复制一个结构,以便它是一个新实例。目前我是这样做的:
auto* psThisEvent = static_cast<SPECIAL_EVENT_S*>(m_lbEvents.GetItemDataPtr(iThisEventIndex));
if (psThisEvent == nullptr)
return;
auto* psNewEvent = new SPECIAL_EVENT_S;
if (psNewEvent == nullptr)
return;
psNewEvent->bEventAllDay = psThisEvent->bEventAllDay;
psNewEvent->bSetReminder = psThisEvent->bSetReminder;
psNewEvent->datEvent = datNewEvent;
psNewEvent->datEventFinishTime = psThisEvent->datEventFinishTime;
psNewEvent->datEventStartTime = psThisEvent->datEventStartTime;
psNewEvent->eType = psThisEvent->eType;
psNewEvent->iForeignLanguageGroupMenuID = psThisEvent->iForeignLanguageGroupMenuID;
psNewEvent->iImageWidthPercent = psThisEvent->iImageWidthPercent;
psNewEvent->iReminderInterval = psThisEvent->iReminderInterval;
psNewEvent->iReminderUnitType = psThisEvent->iReminderUnitType;
psNewEvent->iSMREventType = psThisEvent->iSMREventType;
psNewEvent->iSRREventType = psThisEvent->iSRREventType;
psNewEvent->strEvent = psThisEvent->strEvent;
psNewEvent->strImagePath = psThisEvent->strImagePath;
psNewEvent->strLocation = psThisEvent->strLocation;
psNewEvent->strTextAfterImage = psThisEvent->strTextAfterImage;
psNewEvent->strTextBeforeImage = psThisEvent->strTextBeforeImage;
这是正确的方法吗?我看到了这个问题,但我不确定在这种情况下使用memcpy
是否安全。
我不确定在这种情况下使用 memcpy 是否安全。
你的怀疑是有根据的。SPECIAL_EVENT_S
结构具有不可复制的成员(即无法使用memcpy
正确复制)。例如,它包含多个CString
成员 – 一个具有嵌入式数据缓冲区和指针的类;因此,如果结构只是简单地将内存复制到内存,则销毁一个结构(目标)可能会导致另一个结构(源)中CString
对象的数据缓冲区失效。必须为每个对象调用CString
复制构造函数。(COleDateTime
成员对象也可能如此。
如注释中所述,为SPECIAL_EVENT_S
调用隐式定义的复制构造函数或复制赋值运算符应该会解决这个问题;类似于以下内容:
*psNewEvent = *psThisEvent;
但是,正如您正确指出的那样,您需要在该复制构造函数/赋值之后显式分配datEvent
成员:
psNewEvent->datEvent = datNewEvent;