重载“新”操作员
当我定义类中声明的重载 new 运算符的工作时, 我遇到了以下困惑......
- 在这里,函数的返回类型是“void”,但我 必须引入一个 return 语句...否则我的程序崩溃...为什么会这样?
“void *p”是什么意思
void *myclass::operator new(size_t size) { 无效*p; p=malloc(大小); cout<<"IN 重载新的"; 如果(!p) { bad_alloc ba; 扔吧; } 返回p; }
欢迎澄清。
While I was defining the working of an overloaded new operator declared in a class,
I came across following confusion....
- HERE ,the return type of the function is 'void',yet I
have to introduce a return statement.....otherwise my program crashes....why so? What is meant by "void *p"
void *myclass::operator new(size_t size) { void *p; p=malloc(size); cout<<"IN overloaded new"; if(!p) { bad_alloc ba; throw ba; } return p; }
to the point clarifications are appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
函数的返回类型不是 void,而是 void*(void 指针)。 void 指针是一个通用指针,可以指向任何内容,但不能取消引用它 - 您必须在取消引用它之前将其转换为另一种类型。
如果您不返回 void *,那么您就不会返回指向您分配的内存的指针,并且用户代码将失败。
The return type of the function is not void, its a void* (void pointer). A void pointer is a generic pointer which can point to anything, but it cannot be dereferenced - you have to cast it to another type prior to dereferencing it.
If you don't return the void *, then you're not returning the pointer to the memory you allocated, and the users code will fail.
void*
是一个无类型指针。它是一个可以指向任何东西的指针。请注意,该函数的返回类型不是void
而是void*
。它应该返回一个指向已分配内存的指针。void*
is an untyped pointer. It's a pointer that can point to anything. Note that the return type of this function is notvoid
butvoid*
. It's supposed to return a pointer to the memory that was allocated.重载new的简单演示
重载new的返回类型必须是void*。它应该返回一个指向分配的内存块的开头的指针。即这里它返回 void * 而不是 void(这意味着不返回任何内容)。
Simple demonstration of overloaded new
The return type of the overloaded new must be void*. It is expected to return a pointer to the beginning of the block of memory allocated.ie Here it is returning void * and not void(which means doesnt return anything) .