[英]How do we know if a pointer was allocated with new or new[]?
I'm trying to implement a unique_ptr class in C++, but how to know if the pointer we passed to it was allocated with new
or new[]
without using default_delete
(my school standard doesn't allow c++11).我正在尝试在 C++ 中实现一个 unique_ptr 类,但是如何知道我们传递给它的指针是用new
还是new[]
分配的,而不使用default_delete
(我的学校标准不允许 c++11)。 I mean when you pass your pointer to the constructor like this for example:我的意思是当你将指针传递给构造函数时,例如:
unique_ptr<int> ptr(new int[10]);
how do you know inside of the class if you need to call delete[]
or delete
?如果您需要调用delete[]
或delete
您如何知道类内部?
You can't tell.你不能说。 And neither can std::unique_ptr
. std::unique_ptr
也不能。
Think about it.想想看。 If it could be determined automatically, you wouldn't need two kinds of delete
.如果可以自动确定,则不需要两种delete
。
std::unique_ptr<int> ptr(new int[10]);
is wrong, since it will try to call delete
, rather than delete[]
.是错误的,因为它会尝试调用delete
,而不是delete[]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.