开发者

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

开发者 https://www.devze.com 2022-12-12 17:22 出处:网络
A class has overloaded operators new and delete. 开发者_开发问答new is public, delete is private.

A class has overloaded operators new and delete. 开发者_开发问答new is public, delete is private.

When constructing an instance of this class, I get the following error:

pFoo = new Foo(bar)

example.cpp(1): error C2248: 'Foo:operator delete': cannot access private member declared in class 'Foo'

But there's no call to delete here, so what is going on in the twisted mind of the compiler? :)

  1. What is the reason for the error?
  2. Is it possible to resolve the problem without resorting to a member CreateInstance function?


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()).


Check this. In one of the lower paragraphs it says that new requires delete to be accessable. Basically it says, you can only create objects on the heap, if you can also delete them again.


As per C++ Standards , When you have class with dynamically memory allocation and an exception is raised inside constructor, memory has to be freed to avoid memory leaks.

Here you have defined you own new operator as public , but delete is private .

So compiler is telling you that give me access to delete operator so that i can prevent memory leak if any exception is raised in constructor.

If you don't define your delete operator , then also compiler will give an error and force you to define it.


  • "1.What is the reason for the error?"

    sbi's answer is good.

  • "2.Is it possible to resolve the problem without resorting to a member CreateInstance function?"

    Yes. Create private destructor.


Calling operator new on class will use also delete class if class constructor throws an exception.

If your library does not use exceptions, you can disable exceptions from compiler "-fno-exceptions", then error won't appear anymore. (In Visual studio resides under "C/C++", "Code Generation", "Enable C++ Exceptions" > "No (-fno-exceptions)")

0

精彩评论

暂无评论...
验证码 换一张
取 消