3

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?

8
  • 2
    Where is this in the book? I'd like to try to find it Commented Feb 7, 2017 at 19:03
  • This is the quote from the Item 3. Make copying cheap and correct for objects in containers. Commented Feb 7, 2017 at 19:08
  • It's been a while since I've read Effective STL but either Scott Myers said more to it, and that context isn't in the question, or the book isn't updated for C++11 and beyond. Commented Feb 7, 2017 at 19:08
  • 1
    @StoryTeller: There was never a time when the front and back functions didn't return a reference. Commented Feb 7, 2017 at 19:10
  • 1
    @VardanHovhannisyan What edition of the book? My version (from September 2007) does not suggest that front() and back() return copies. Commented Feb 7, 2017 at 19:12

2 Answers 2

5

This was actually an error in an earlier edition of the book. From the errata:

! 6/29/01 jk 20 The first para of Item 3 is incorrect: front 7/25/04 and back do NOT return copies of elements, they return references to elements. I removed all mention of front and back. 

So the explanation of the sentence is: woops, time to get a new edition!

Sign up to request clarification or add additional context in comments.

Comments

2

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++.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.