[英]Can I use a name of a deleted pointer?
Is it allowed to use a pointer's name of a pointer once deleted?是否允许在删除后使用指针的名称?
This code, for instance, won't compile.例如,此代码不会编译。
int hundred = 100;
int * const finger = &hundred;
delete finger;
int * finger = new int; // error: conflicting declaration 'int* finger'
This won't either:这也不会:
int hundred = 100;
int * const finger = &hundred;
delete finger;
int finger = 50; // error: conflicting declaration 'int finger'
No. The int *
is still an living object.不。
int *
仍然是一个活的 object。 The lifetime of the int
that it pointed to has ended.它指向的
int
的生命周期已经结束。
Note that注意
int hundred = 100;
int * const finger = &hundred;
delete finger;
has undefined behaviour, as you have attempted to delete
an object that was not allocated by new
.具有未定义的行为,因为您试图
delete
未由new
分配的 object 。
In general, new
and delete
should not appear in C++ programs.一般来说,
new
和delete
不应该出现在 C++ 程序中。 Owning pointers should be std::unique_ptr
(or rarely std::shared_ptr
or other user-defined smart pointer type).拥有指针应该是
std::unique_ptr
(或者很少是std::shared_ptr
或其他用户定义的智能指针类型)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.