使用 MFC 将结构复制到另一个结构

Copying a structure to another structure with MFC

我有这样的结构:

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 是否安全。

I am not sure if it is safe to use memcpy in this case.

你的怀疑是有根据的。 SPECIAL_EVENT_S 结构的成员不可 简单复制(即不能正确 使用memcpy 复制)。例如,它包含几个 CString 成员——一个带有嵌入式数据缓冲区和指针的 class;因此,如果结构只是简单地从内存复制到内存,那么破坏一个结构(目标)将可能导致另一个结构(源)中 CString 对象的那些数据缓冲区无效。您必须 为这些对象的每个 调用CString 复制构造函数。 (COleDateTime 成员对象也是如此。)

如评论中所述,为 SPECIAL_EVENT_S 调用隐式定义的复制构造函数或复制赋值运算符应该 处理此问题;类似于:

*psNewEvent = *psThisEvent;

但是,正如您正确指出的那样,您随后需要明确分配 datEvent 成员 after 该副本 constructor/assignment:

psNewEvent->datEvent = datNewEvent;