【问题标题】:Does new return (void *) in C++?在 C++ 中新返回 (void *) 吗?
【发布时间】:2013-04-27 01:20:42
【问题描述】:

这是一个简单的问题:

使用 new 运算符是否返回类型为 (void *) 的指针? 参考What is the difference between new/delete and malloc/free? 答案 - 它说new returns a fully typed pointer while malloc void *

但是根据http://www.cplusplus.com/reference/new/operator%20new/

throwing (1)    
void* operator new (std::size_t size) throw (std::bad_alloc);
nothrow (2) 
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) throw();
placement (3)   
void* operator new (std::size_t size, void* ptr) throw();

这意味着它返回一个(void *)类型的指针,如果它返回(void *)我从来没有见过像MyClass *ptr = (MyClass *)new MyClass;这样的代码

我很困惑。

编辑

http://www.cplusplus.com/reference/new/operator%20new/为例

std::cout << "1: ";
  MyClass * p1 = new MyClass;
      // allocates memory by calling: operator new (sizeof(MyClass))
      // and then constructs an object at the newly allocated space

  std::cout << "2: ";
  MyClass * p2 = new (std::nothrow) MyClass;
      // allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)
      // and then constructs an object at the newly allocated space

所以MyClass * p1 = new MyClass 调用operator new (sizeof(MyClass)) 并且由于throwing (1)
void* operator new (std::size_t size) throw (std::bad_alloc);
如果我正确理解语法,它应该返回(void *)

谢谢

【问题讨论】:

  • @DyP 好的.. 明白了.. 你想说什么The new-expression (new int) uses an allocation function (operator new). The allocation function only provides storage, new-expression new type-id returns a pointer to type-id (or throws).. 谢谢

标签: c++


【解决方案1】:

您混淆了operator new(它确实返回void*)和new 运算符(它返回一个全类型指针)。

void* vptr = operator new(10); // allocates 10 bytes
int* iptr = new int(10); // allocate 1 int, and initializes it to 10

【讨论】:

  • 标准将后者称为new-expression
  • 一种思考方式是new 表达式将内存“转换”或“投射”到对象:void 指针进入,对象指针出现。
  • john 引用 cplusplus.com/reference/new/operator%20new std::cout &lt;&lt; "1: "; MyClass * p1 = new MyClass; // allocates memory by calling: operator new (sizeof(MyClass)) // and then constructs an object at the newly allocated space 它调用 operator new (sizeof(MyClass)) ,所以基本上它应该根据你的论点返回 (void *)
  • @GauravK 新表达式 (new int) 使用 分配函数 (operator new)。分配函数只提供存储,new-expression new type-id 返回一个pointer to type-id(或throws)。
  • @KerrekSB - “转换”,而不是“转换”。 &lt;g&gt; 在我通常的迂腐模式下:cast 是您在源代码中编写的内容,用于告诉编译器进行转换
【解决方案2】:

void * 在赋值期间不需要转换为更高的类型,只有在存在 void * 之前的旧 c 代码需要转换,因为旧的 malloc 签名返回了 char *

【讨论】:

    【解决方案3】:

    new 将返回一个您正在创建实例的类型的指针。 operator new 返回指向 void 的指针。 new 相当普遍,而 operator new 则更独特一些。

    【讨论】:

      猜你喜欢
      • 2017-02-28
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 2016-08-28
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      相关资源
      最近更新 更多