c++ - delete 对象的指针
ringa_lee
ringa_lee 2017-04-17 12:00:23
0
3
859
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_lee
ringa_lee

ringa_lee

reply all(3)
刘奇
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()...

Peter_Zhu

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

PHPzhong

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!