Does MFC CList support the copy assignment?

2.1k Views Asked by At

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

There are 1 best solutions below

2
On BEST ANSWER

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