what use does auto-pointers have as opposed to declaring variables on the stack? |
I should have written that line 18 as:
std::unique_ptr<Box> ptr2 = std::make_unique<Box>(6.0,5.0,5.0);
Yes, both ptr and ptr2 are on the stack. Both cease to exist when the scope ends. The thing is that you might exit the scope from multiple points:
1 2 3 4 5 6 7 8 9 10
|
int foo() {
Bar bar = new ...;
// use bar
if ( cond ) {
// use bar
return 0;
}
// use bar
return 1;
}
|
If Bar is a raw pointer, then you should deallocate before line 9
and before line 6.
If Bar is a "smart pointer", then its destructor can call delete on every exit point.
Smart pointers can transfer ownership, so the stack variable that originally points to the dynamically allocated object does not have to be the one that actually deletes it.
Then there is the std::shared_ptr. Multiple pointers can point to same object. If they are shared_ptr, they know each other and the lifetime of the object is until the last one of these pointer is destroyed.
Pointers (both raw and smart) can be either valid or invalid. One should not dereference an invalid pointer. One should thus test pointer before using it.
anup30 assigns 0 to ptr to show that it is invalid. If you don't do that after delete, and test the pointer later, then it still has a valid looking address even though memory in that location has already been deallocated.
No munchkin hero is happy with just one blade!
1 2 3 4 5 6 7 8 9 10 11 12
|
std::vector<Weapon> belt;
belt.emplace_back( "Vorbal blade" );
belt.emplace_back( "Mjölnir" );
belt.emplace_back( "daffodils" );
if ( 0 < belt.size() ) // I have weapons
{
if ( belt.begin()->isBroken() ) // first weapon has turned to garbage
{
belt.erase( belt.begin() ); // deletes the first weapon
}
}
|