这是一个简单的问题:
使用 new 运算符是否返回类型 (void *) 的指针?参考new/delete和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 *)
谢谢