重载“新”操作员

发布于 2024-12-20 08:23:33 字数 328 浏览 2 评论 0原文

当我定义类中声明的重载 new 运算符的工作时, 我遇到了以下困惑......

  1. 在这里,函数的返回类型是“void”,但我 必须引入一个 return 语句...否则我的程序崩溃...为什么会这样?
  2. “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....

  1. HERE ,the return type of the function is 'void',yet I
    have to introduce a return statement.....otherwise my program crashes....why so?
  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

月下客 2024-12-27 08:23:33

函数的返回类型不是 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.

冬天旳寂寞 2024-12-27 08:23:33

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 not void but void*. It's supposed to return a pointer to the memory that was allocated.

白昼 2024-12-27 08:23:33

重载new的简单演示

void* operator new(size_t num)
{
 return malloc(num);
 }

重载new的返回类型必须是void*。它应该返回一个指向分配的内存块的开头的指针。即这里它返回 void * 而不是 void(这意味着不返回任何内容)。

Simple demonstration of overloaded new

void* operator new(size_t num)
{
 return malloc(num);
 }

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文