公共运营商新,私人运营商删除:获得C2248“不能访问私有成员”当使用新 [英] Public operator new, private operator delete: getting C2248 "can not access private member" when using new

查看:144
本文介绍了公共运营商新,私人运营商删除:获得C2248“不能访问私有成员”当使用新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类有重载的操作符 new delete 是公开的,删除是私人的。

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':无法访问在类中声明的私有成员'Foo'

但是这里没有调用 delete 扭曲的编译器头脑? :)

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


  1. 错误的原因是什么?

  2. 是否可以不使用成员 CreateInstance 函数来解决问题?

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


推荐答案

当你做 new Foo() c $ c> operator new 被调用来分配内存,然后调用 Foo 的构造函数。如果该构造函数抛出,因为你不能访问已经分配的内存,C ++运行时会通过将它传递到相应的 operator delete 来处理它。这就是为什么你总是必须为每个运算符new 实现一个匹配的运算符delete ,这就是为什么它需要可访问。

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.

作为出路,您可以将它们都设为私有,并从公共成员函数中调用 operator new create())。

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

这篇关于公共运营商新,私人运营商删除:获得C2248“不能访问私有成员”当使用新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆