在C ++中新的返回(void *)? [英] Does new return (void *) in C++?
问题描述
这是一个简单的问题:
使用new运算符返回类型为(void *)的指针吗?
参考新的/ delete和malloc / free?答案 - 它说: new返回一个完全类型的指针malloc void *
Does using new operator return a pointer of type (void *)?
Referring to What is the difference between new/delete and malloc/free? answer - it says new returns a fully typed pointer while malloc void *
但根据 http://www.cplusplus.com/reference/new/操作符%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 *)从未见过类似MyClass的代码* ptr =(MyClass *)new MyClass;
which means it returns a pointer of type (void *), if it returns (void *) I have never seen a code like MyClass *ptr = (MyClass *)new MyClass;
我很困惑。
EDIT
根据 http://www.cplusplus.com/reference/new/operator%20new/ example
As per 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
因此 MyClass * p1 = new MyClass
调用 (myClass))
,因为 throwing(1)
如果我理解正确的语法,它应该返回
void * operator new(std :: size_t size)throw(std :: bad_alloc); (void *)
。
So MyClass * p1 = new MyClass
calls operator new (sizeof(MyClass))
and since throwing (1)
it should return
void* operator new (std::size_t size) throw (std::bad_alloc);(void *)
if I understand the syntax correctly.
/ p>
Thanks
推荐答案
您会混淆 operator new
c> void * )和 new
运算符(返回完全类型的指针)。
You are confusing operator new
(which does return void*
) and the new
operator (which returns a fully-typed pointer).
void* vptr = operator new(10); // allocates 10 bytes
int* iptr = new int(10); // allocate 1 int, and initializes it to 10
这篇关于在C ++中新的返回(void *)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!