Public operator new, private operator delete: getting C2248 quot;can not access private memberquot; when using new(公共运营商新建,私有运营商删除:获取C2248“无法访问私有成员当使用新)
问题描述
一个类具有重载运算符 new 和 delete.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): 错误 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? :)
- 错误的原因是什么?
- 是否可以在不求助于成员
CreateInstance函数的情况下解决问题?
- What is the reason for the error?
- Is it possible to resolve the problem without resorting to a member
CreateInstancefunction?
推荐答案
当你执行 new Foo() 时,会发生两件事:首先调用 operator new 来分配内存,然后调用 Foo 的构造函数.如果该构造函数抛出异常,因为您无法访问已分配的内存,C++ 运行时将通过将其传递给适当的 operator delete 来处理它.这就是为什么你总是必须为你编写的每个 operator new 实现一个匹配的 operator 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.
作为一种出路,您可以将它们都设为私有并从公共成员函数(如 create())调用 operator new.
As a way out you could make both of them private and invoke operator new from a public member function (like create()).
这篇关于公共运营商新建,私有运营商删除:获取C2248“无法访问私有成员"当使用新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:公共运营商新建,私有运营商删除:获取C2248“无法访问私有成员"当使用新
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
