ccs said:
Why should I use auto_ptr if all the "new" and "delete" handles things
properly
You shouldn't. However, if new and delete don't handle things properly
then you should. For example:
void fnc() {
int* a = new int;
int* b = new int;
// do something
delete b;
delete a;
}
Here new and delete don't handle things properly. If the second new
throws, then the first block of memory won't be deleted. If any code
inside "do something" throws, neither block will be deleted. Instead:
void fnc() {
auto_ptr<int> a( new int );
auto_ptr<int> b( new int );
// do something
}
Now the blocks of memory will get deleted properly.
What is it for auto_ptr to have release()? When should call it?
Given this function:
Viehicle* func() {
// do some side effect
return new Car;
}
If someone is calling func just for the side effect, then they will:
func();
and memory will leak. However:
auto_ptr<Vechicle> func() {
// do some side effect
return auto_ptr<Vechile>( new Car );
}
Now the call:
func();
Won't leak memory because the auto_ptr will clean up after itself. But
I'll need release if I want to get that vehicle...
Vehicle* v;
v = func().release();
Why some people suggest using std::vector to handle 2-dimension arrays?
I'm not one of those people, I think you should use a custom 2D array
class that uses std::vector internally.
Does it have too much overhead compared to using "new" and "delete" directly?
No. There is aboslutly no reason why using vector should have any more
overhead than creating and maintaining dynamic arrays on your own would.