Does MFC CList support the copy assignment?

醉酒当歌 提交于 2019-12-12 17:12:55

问题


I've looked up the CList definition in MSVC afxtempl.h and document on MSDN. I did not see the CList& operator=(const CList&); is defined.

Can I directly use operator= to copy a CList object like this?

 CList<int> a = b;

Or I should iterate the source CList manually from head to tail and AddTail on the target CList?

 for(POSITION pos = a.HeadPosition(); pos; )
 {
      const auto& item = a.GetNext(pos);
      b.AddTail(item);
 }

Any suggestions will be helpful. Thanks.


回答1:


If the copy assignment operator isn't defined, then it isn't defined and can't be used. That's true for CList, as you've already observed, so no, you can't just use operator= to copy a CList object. If you want a deep copy of the collection, you will need to write a function to do so manually.

But consider whether you really want a deep copy. Most of the time, you'll want to pass collection types by reference, rather than by value. This is especially true in MFC, where they can contain objects derived from CObject that can't necessarily be copied. In fact, you'll notice that copying is explicitly disallowed by the CObject class, using a private copy constructor and assignment operator:

   // Disable the copy constructor and assignment by default so you will get
   //   compiler errors instead of unexpected behaviour if you pass objects
   //   by value or assign objects.
private:
   CObject(const CObject& objectSrc);              // no implementation
   void operator=(const CObject& objectSrc);       // no implementation


来源:https://stackoverflow.com/questions/23210250/does-mfc-clist-support-the-copy-assignment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!