At-most-once: A pointer to any specific object can exist in at most one container object at any point in time.
Existence: An object must be dynamically allocated before a pointer to it is inserted.
Ownership: Once a pointer to an object is inserted, that objects becomes property of the container. No one else may use or modify it in any way.
Conservation: When a pointer is removed from a container, either the pointer must be inserted into some container, or its referent must be deleted.
These are the respective definitions I’ve been given. I’m having trouble understanding the various terminology used in each of them, and I was hoping someone here could explain exactly what each one means and how they’re used to ensure good programming practice.
As an example, assume you have the following class definitions:
Having two instances of
Containerwith a pointer to the same instance ofItemwould violate this:Dynamically allocating an object generally means creating a new instance of an object with the operator
new, which returns a pointer to the newly created object allocated on heap memory (as opposed to stack). Two examples of a violation of this are:When an object exists in memory, any object or function that has a pointer or reference to the object could potentially modify it (unless the pointer or reference is declared
const):This means that when the container no longer wants to “own” (defined in exactly the same sense as above) the item instance it points to, it must either transfer “ownership” to another container, or delete the item. The following modification to the
Containerclass implements this behavior: