Search code examples
c++stleffective-c++

Container front and back behavior


Here is the quote from "Effective STL":

When you get an object from a container (via. e.g., front or back), what you set is a copy of what was contained. Copy in, copy out. That's the STL way.

I have had a hard time understanding this part. As far as I know front returns the reference of the first element (at least for std::vector). Could you please explain above sentence?


Solution

  • The idea with a statement like that is that when you want to get an element out of the container, you don't keep a reference or pointer to the element in the container, you create a copy of it (from the reference those methods return). The function returns, for back() and front(), are secondary concerns and likely confuse the issue - even the errata removed the mention of them.

    Containers can undergo reallocation (especially vector) with you not necessarily being notified by the container, the elements are moved in memory and suddenly you have an invalid reference or pointer.

    Bear in mind the time of the advice, before move semantics and movable objects etc. But the general principle still applies, don't keep references or pointers to objects that could become invalid.

    "Value semantics" is a strong theme that not only runs through the standard library, but the whole of C++.