Home  >  Q&A  >  body text

c++ - 为什么delete后的指针不能解引用输出?而被智能指针的析构释放的指针可以解引用输出(尽管拿到的是垃圾数据)呢?

    //方案1
    int *ip = new int(42);
    int *alpha = new int(10);
    shared_ptr<int>q1 (alpha);
    shared_ptr<int> p1(ip);
    p1 = q1;                           //将引用计数置为0
    cout <<"ip(释放后):" <<*ip << endl; //可以输出

    //方案2
    int *test1 = new int(4);
    delete(test1);
    cout << *test1 << endl;              //提示内存错误,读取位置发生访问冲突
    
    //方案3
    int a=10;
    int *test2=&a;
    delete(test2);
    cout<< *test2<< endl;               //提示_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
    

请问这是为什么?
delete和智能指针释放内存的机制有什么区别?
方案2和方案3有什么区别?为什么错误不一样呢?

PHPzPHPz2765 days ago626

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 14:31:14

    1. shared_ptr also calls delete by default, so in theory there is no difference from the delete mechanism

    2. The behavior of accessing again after deletion is uncertain. It can happen under any circumstances. For example, if your memory is not used by anyone else, then the access will still have the original value, or it will become 0; if it is used by someone else, If used, anything will happen. This is the so-called wild pointer. So it is normal that the behavior of share_ptr and delete here is different. You can run it multiple times to see the result.

    3. A in plan 2 is allocated on the heap, and plan 3 is allocated on the stack. delete can only be used to release the memory on the heap (or the memory from new), and cannot release the memory on the stack. , so the _BLOCK_TYPE_IS_VALID error will be reported. The memory on the stack is automatically released by the system when the function exits

    reply
    0
  • Cancelreply