简体   繁体   中英

rule of thumb for new and delete

I was wondering what the rule of thumb for new and delete is. I always thought that every time I call new , I should have a delete .

In the case below, if I include the destructor however, I get a bad excess error. If I don't include the destructor , my code works fine.

struct Foo
 {
     Foo(int A, int B)
     {
          bar = new std::vector< std::vector < int > >(A, std::vector<int>(B,2);
          //creates a vector of A vectors where each nested vector contains the number 2 B times. 
     }

     ~Foo() //Get bad access error if destructor included in code. 
     {
          delete[] bar;
     }     

     std::vector< std::vector < int > > *bar;
 };

int main()
{
    Foo X;

    return 0;
}

It should be delete bar; not delete [] bar;

Add another rule to your list of rules.

The delete line should have a [] only if the new line has a [some number]

In your case the new line does not have a [some number]

 bar = new std::vector< std::vector < int > >(A, std::vector<int>(B,2);

So your delete line also should not have one.

The above class might be better written as:

struct Foo   
 {
     Foo(int A, int B)
       :  bar(A, std::vector<int>(B,2)) //creates a vector of A vectors where each nested vector contains the number 2 B times. 
     {}
     // Default copy
     // Default destructor.

     std::vector< std::vector < int > > bar;
 };

This avoids explicit new and delete ; often the best rule of thumb for using them correctly!

With unmanaged code like c++ the rule of thumb is whatever is required by your design.

In general, it's a good idea to clean up your objects to avoid memory leaks, but you could have a situation where you want to keep something in memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM