Deleting C++ pointers to an object

前端 未结 9 1185
攒了一身酷
攒了一身酷 2021-01-26 20:06

I thought that the delete command would free up memory I allocated. Can someone explain why it seems I still have the memory in use after delete?

class Test
{
pu         


        
9条回答
  •  盖世英雄少女心
    2021-01-26 20:29

    Pointers are a container for an address in memory. You can always use a declared pointer, but unless it's initialized to memory that you own, expect confusion and worse.

    Test *e;
    e->time = 2;
    

    also compiles and won't work. Minimize this type of confusion so:

    {
      boost::scoped_ptr e(new Test);
    
      e->time = 1;
      cout << e->time << endl;
    
      e->time = 2;
      cout << e->time << endl;
    }
    

    No new/delete needed, just enclosing braces to define the scope, and an appropriate smart pointer.

提交回复
热议问题