Why disable CObject's copy constructor and assignment

后端 未结 2 1831
小鲜肉
小鲜肉 2020-12-18 00:36

The MFC\'s root object CObject\'s copy constructor and assignment are disabled by default.

  • In MSDN, there is a description

The st

2条回答
  •  误落风尘
    2020-12-18 01:23

    Consider the following:

    class CMyHandle : public CObject
    {
        HANDLE hWin32;
    public:
        CMyHandle()
        {
            hWin32 = SomeFunctionThatMakesHandle();
        }
        ~CMyHandle()
        {
            CloseHandle(hWin32);
        }
    };
    

    Now, if you copy CMyHandle, the handle ends up getting closed twice, and after the either one of the CMyHandle instances is destroyed, the other instance becomes invalid.

    Since a large number of MFC's classes manage handles, this makes sense to force the creator of the class to explicitly override to create copy constructors and copy assignment operators.

    EDIT: For example:

    int main()
    {
        CMyHandle h1; //CMyHandle's constructor initializes the handle
        {
            CMyHandle h2(h1); //Memberwise copy into h2. In this case, it copies the
                              //handle
        } //h2 destroyed, closes handle
        //h1 is now invalid (because the underlying handle was closed)!
    }
    

提交回复
热议问题