简体   繁体   English

我们如何知道一个指针是用 new 还是 new[] 分配的?

[英]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.

相关问题 我如何知道是否使用new在堆上分配了对象? - How do I know if an object is allocated on the heap using new? 我们如何释放已分配的内存,如下所示:A&o = *(new A)? - How do we deallocate memory that has been allocated like this: A& o = *(new A)? c ++删除用new分配的char指针 - c++ deleting char pointer allocated with new 为什么我们要删除new分配的内存? - Why should we delete the memory allocated by new? 我怎么知道一个指针是否已经通过“ new”分配了数据? - How do I know if a pointer has been assigned data via 'new'? 如何将新节点插入单链表,我们没有指向其头部的指针? - How to insert a new node to a single-linked list, where we do not have a pointer pointed to its head? 如何删除使用placement new分配的对象 - how do you delete an object allocated with placement new new / malloc如何记住分配的数据量? - How do new/malloc seem to remember amount of data allocated? 如何释放 new[] 分配的 memory? - How to free memory allocated by new[]? 我们是否需要为“placement new”分配的“简单POD类”显式调用析构函数? - Do we need to explicitly call the destructor for the “simple POD classes” allocated with “placement new”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM