微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用 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;

这是解决这个问题的正确方法吗?我看到了这个 question,但我不确定在这种情况下使用 memcpy 是否安全。

解决方法

我不确定在这种情况下使用 memcpy 是否安全。

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

正如评论中提到的,为 SPECIAL_EVENT_S 调用隐式定义的复制构造函数或复制赋值运算符应该处理这个问题;类似的东西:

*psNewEvent = *psThisEvent;

但是,正如您正确指出的那样,您将需要在复制构造函数/赋值之后显式分配 datEvent 成员

psNewEvent->datEvent = datNewEvent;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。