Reputation: 146
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;
}
Upvotes: 0
Views: 174
Reputation: 6834
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!
Upvotes: 6
Reputation: 2232
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.
Upvotes: 0
Reputation: 14039
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.
Upvotes: 7