search

Home  >  Q&A  >  body text

c++ - delete 对象的指针

class A
{
public:
    A()
    {
        i =10;
    }
private:
    int i;
};
int main(){

    A a;
    A *p = &a;
    delete p;
    return 0;
}

请问这段程序运行为什么出错?
运行结果:free(): invalid pointer: 0xbfc367b8 ***

ringa_leeringa_lee2767 days ago866

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-17 12:02:23

    cppint main(){
        A a;
        A *p = &a;
        delete p;
        return 0;
    }
    

    A a produces an A object, and it seems that delete &a is right to release the memory space of a. But don’t forget that when the main() {} function ends, the local variable in it, which is a, will be automatically released. With the delete you wrote, it will be released twice, so an error will be reported.

    Generally, new corresponds to delete. new is useless and delete is not needed at all. And try to ensure that new and delete are in the same code block; if you need to perform operations in two places, it is usually new in the constructor and delete in the destructor; or new in create(), Delete in delete() or release(), and pay attention to the pairing of create() and delete()...

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 12:02:23

    Addresses that have not been new do not need to be deleted. New and delete should be paired

    reply
    0
  • PHPz

    PHPz2017-04-17 12:02:23

    new stores the memory of the object in , that is, in user control. The memory is managed by the user, so to release the memory, use delete
    And
    A a; stores the memory of the object in , which is the system control. The release of memory is managed by the system, so using delete will report an error. The address to be released is not controllable by the user

    reply
    0
  • Cancelreply