【问题标题】:Can I use a name of a deleted pointer?我可以使用已删除指针的名称吗?
【发布时间】:2021-05-07 18:07:14
【问题描述】:

是否允许在删除后使用指针的名称?

例如,此代码不会编译。

    int hundred = 100;
    int * const finger = &hundred;
    delete finger;

    int * finger = new int; // error: conflicting declaration 'int* finger'

这也不会:

    int hundred = 100;
    int * const finger = &hundred;
    delete finger;

    int finger = 50; // error: conflicting declaration 'int finger'

【问题讨论】:

  • 指针本身没有被删除,只有它所指向的东西。所以指针仍然存在,你不能在同一范围内使用该名称来做不同的事情。另外请不要删除不是您使用new 创建的内容,这是等待发生的崩溃。
  • 谢谢。现在我明白了。

标签: c++11 pointers redeclare


【解决方案1】:

没有。 int * 仍然是一个活的对象。它指向的int 的生命周期已经结束。

注意

int hundred = 100;
int * const finger = &hundred;
delete finger;

具有未定义的行为,因为您试图 delete 一个不是由 new 分配的对象。

一般来说,newdelete 不应出现在 C++ 程序中。拥有指针应该是std::unique_ptr(或者很少是std::shared_ptr 或其他用户定义的智能指针类型)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    相关资源
    最近更新 更多