The Standard Template Library documentation for list says:
void push_back ( const T& x );
Add element at the end Adds a new element at the end of the list,
right after its current last element. The content of this new element
is initialized to a copy of x.
These semantics differ greatly from the Java semantics, and confuse me. Is there a design principle in the STL that I’m missing? “Copy data all the time”? That scares me. If I add a reference to an object, why is the object copied? Why isn’t just the object passed across?
There must be a language design decision here, but most of the commentary I’ve found on Stack Overflow and other sites focuses on the exception throwing issues associated with the fact that all this object copying can throw exceptions. If you don’t copy, and just handle references all those exception problems go away. Very confused.
Please note: in this legacy code base I work with, boost is not an option.
The STL always stores exactly what you tell it to store.
list<T>is always a list ofTso everything will be stored by-value. If you want a list of pointers, uselist<T*>, that will be similar to the semantics in Java.This might tempt you to try
list<T&>, but that is not possible. References in C++ have different semantics than references in Java. In C++, references must be initialized to point to an object. After a reference is initialized, it will always point to this object. You can never make it point to a different object. This makes it impossible to have a container of references in C++. Java references are more closely related to C++ pointers, so you should uselist<T*>, instead.