[英]C++ use operator delete for auto (stack) pointer
Must I use operator delete
for stack pointer? 我必须对堆栈指针使用运算符
delete
吗?
For example: 例如:
User * p = new User;
delete p; //needed?
When you use delete
you are not deleting the pointer, so it makes no difference whether it is a stack pointer or any other kind of pointer. 使用
delete
您不会删除指针,因此无论是堆栈指针还是任何其他类型的指针都没有区别。
When you use delete
you are deleting the block of memory pointed by the pointer. 使用
delete
您将删除指针指向的内存块。 If that block was allocated with new
, then it's always on the heap. 如果该块分配有
new
,则它总是在堆上。 (If it was not allocated with new
, then you should not delete
it.) (如果未使用
new
分配它,则不应delete
它。)
The other angle is that no, you must not use operator delete
, because you should never use naked pointers in non-library code. 另一个角度是,不能, 不能使用运算符
delete
,因为永远不要在非库代码中使用裸指针。
In modern C++, your example should be: 在现代C ++中,您的示例应为:
std::unique_ptr<User> p = std::make_unique<User>();
No delete
and no new
in sight. 没有
delete
,也没有new
发现。
Note : in this particulate case, make_unique
could be substituted for new
painlessly, but since in other examples it might not be, it's a good practice to teach yourself - make_unique
is a function to use. 注意 :在这种情况下,可以用
make_unique
地替换new
,但是由于在其他示例中可能不是这样,因此make_unique
是一个好习惯make_unique
是要使用的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.