What is items vector size and how it's arrangement now? The same. The function call does not change the vector contents nor size at all. It just frees the memory the pointer is pointing to.
Is it okay to do this? More precisely: Is it legal C++? Yes. Is it good style programming? No. Let me elaborate on the latter:
There should be a separation of concerns: Who's responsible for memory management? The container or the user of the class
Item
or the classItem
itself?Typically the container or user should do that, because he knows what's going on.
What's the way to do that? Memory management in modern and safe C++ code is mostly done using smart pointers like
std::shared_ptr
andstd::unique_ptr
and containers likestd::vector
andstd::map
.If the class
Item
is a value type (that means you can simply copy it and it has no polymorphic behavior in terms of virtual functions), then just usestd::vector<Item>
instead for your code. Destructors will be called automatically as soon as an element is removed from the container. The container does it for you.If the class
Item
has polymorphic behavior and can be used as a base class, then usestd::vector<std::unique_ptr<Item>>
orstd::vector<std::shrared_ptr<Item>>
instead and prefer thestd::unique_ptr
solution, because it adds less overhead. As soon as you stop referring to an object, it will be deleted automatically by the destructor of the smart pointer you are using. You (almost) don't need to worry about memory leaks anymore.The only way you can produce memory leaks is that you have objects that contain
std::shared_ptrs
that refer to each other in cyclic way. Usingstd::unique_ptrs
can prevent this kind of trouble. Another way out arestd::weak_ptrs
.
Bottom line: Don't provide a function suicide()
. Instead put the responsibility solely into the hands of the calling code. Use standard library containers and smart pointers to manage your memory.
Edit: Concerning the question in your edit. Just write
items.erase( items.begin() + 1 );
This will work for all types: std::vector
of values or pointers. You can find a good documentation of std::vector
and the C++ Standard library here.