为什么新的操作符允许返回* void到每个指针类型? [英] Why is the new operator allowed to return *void to every pointer-type?

查看:110
本文介绍了为什么新的操作符允许返回* void到每个指针类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,不允许在没有显式转换的情况下为任何整数指针指定void *指针。这需要使用static_cast。

In C++ it is not allowed to assign an void* pointer to any integral pointer without an explicit cast. This requires the use of an static_cast.

但是这是什么:

int* iptr = new int;

我知道新运算符定义如下:

I know that new operator is defined as following:

void* operator new(size_t);

C ++如何处理?
我知道这是一个基本问题,但很重要。我也知道低级代码必须使用void。但是这种分配如何合法呢? iptr是指向int的指针,new返回一个指向void的指针,它应该触发一条类似error:invalid from void *'到'int *'[-fpermissive]的消息。

How does C++ handle this? I know that this is a basic question, but important. I also know that low-level code must use void. But how can this assignment be legal? iptr is a pointer to an int and new returns a pointer to void, which should trigger a message like "error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]".

推荐答案

您已混淆运算符和运算符新功能。没有问题,每个人都。它们几乎是一样的,除了它们是不同的。

You have confused the new operator and the operator new function. No problem, everybody does. They are almost the same, except that they are different.

函数 void * operator new(size_t)

void* raw_memory = ::operator new(42);

这是一个有些奇怪的名字的普通函数。

It is an ordinary function with somewhat weird name.

运算符不是函数,而不是函数调用。它是一个单独的语言结构。它需要原始内存(通常由 void * operator new(size_t)函数返回),并通过调用构造函数将其转换为对象。

The new operator is not a function and not a function call. It's a separate language construct. It takes raw memory (normally, one returned by the void* operator new(size_t) function) and turns it into an object by calling a constructor. It then returns a properly typed pointer to the newly-created object.

Fish* f = new Fish;

UPDATE 当然,还有 delete 运算符(与运算符相反)和 void运算符delete(void *)函数> void * operator new(size_t) function)。

UPDATE Naturally, there is also the delete operator (the opposite of the new operator) and the void operator delete(void*) function (the opposite of the void* operator new(size_t) function).

还有新[] 运算符, delete [] 运算符, void * operator new [](size_t)函数和 void operator delete [](void *)它们处理对象数组(而不是单个对象)。

There are also the new[] operator, the delete[] operator, the void* operator new[](size_t) function, and the void operator delete[](void*) function; they deal with arrays of objects (as opposed to individual objects).

还有所谓的placement new形式,不会调用任何 operator new 函数用于新鲜内存,但是需要一个明确的指向原始内存的指针。它们没有相应的内置删除表单。你可以自己滚动,如果你这么倾向,但我拒绝谈论任何这一点,同时清醒。

There are also so-called "placement new" forms that do not call any of the operator new functions for fresh memory, but instead require an explicit pointer to raw memory. They have no corresponding built-in "delete" forms. You can roll your own if you are so inclined, but I refuse to talk about any of this while being sober.

这篇关于为什么新的操作符允许返回* void到每个指针类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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