Deleting a pointer in C++

后端 未结 6 1354
旧巷少年郎
旧巷少年郎 2020-11-28 01:11

Context: I\'m trying to wrap my head around pointers, we just saw them a couple of weeks ago in school and while practicing today I ran into a silly? issue, it can be super

6条回答
  •  迷失自我
    2020-11-28 01:45

    int value, *ptr;
    
    value = 8;
    ptr = &value;
    // ptr points to value, which lives on a stack frame.
    // you are not responsible for managing its lifetime.
    
    ptr = new int;
    delete ptr;
    // yes this is the normal way to manage the lifetime of
    // dynamically allocated memory, you new'ed it, you delete it.
    
    ptr = nullptr;
    delete ptr;
    // this is illogical, essentially you are saying delete nothing.
    

提交回复
热议问题