【发布时间】: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++