这是一个简单的问题:
使用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();
Run Code Online (Sandbox Code Playgroud)
这意味着它返回一个类型为(void*)的指针,如果它返回(void*)我从未见过像MyClass*ptr =(MyClass*)new MyClass这样的代码;
我很困惑.
编辑
根据http://www.cplusplus.com/reference/new/operator%20new/ example
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
Run Code Online (Sandbox Code Playgroud)
所以MyClass * p1 = new MyClass调用operator new (sizeof(MyClass)),因为如果我正确理解语法,它应该返回.throwing (1)
void* operator new (std::size_t size) throw (std::bad_alloc);(void *)
谢谢
joh*_*ohn 15
你很困惑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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2265 次 |
| 最近记录: |