Public operator new, private operator delete: getting C2248 “can not access private member” when using new

前端 未结 5 796
自闭症患者
自闭症患者 2020-11-27 22:33

A class has overloaded operators new and delete. new is public, delete is private.

When constructing an instance

5条回答
  •  眼角桃花
    2020-11-27 23:09

    When you do new Foo() then two things happen: First operator new is invoked to allocate memory, then a constructor for Foo is called. If that constructor throws, since you cannot access the memory already allocated, the C++ runtime will take care of it by passing it to the appropriate operator delete. That's why you always must implement a matching operator delete for every operator new you write and that's why it needs to be accessible.

    As a way out you could make both of them private and invoke operator new from a public member function (like create()).

提交回复
热议问题