0

I'm reading Herb Sutter's C++ Coding Standards item 79:

Store objects of value in containers: Containers assume they contain value-like types, including value types (held directly), smart pointers, and iterators.

I'm afraid that I didn't get the idea of why.

When Sutter says "contain", does he mean "own"? like "Containers assume they own value-like types"?

Besides value types, smart pointers, and iterators, what else types can be stored? For example, reference? Why reference is not recommended to be stored in containers?

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • For question 2, no you can't have a container of a reference type: https://stackoverflow.com/questions/922360/why-cant-i-make-a-vector-of-references – Ranoiaetep Dec 25 '21 at 12:28
  • The book is released in [2004](https://www.oreilly.com/library/view/c-coding-standards/0321113586/) (pre-c++11) and by value-like the author means copyable in a proper way: not like (removed now) `auto_ptr` and he suggests storing proper smart pointers or raw pointers for non-copyable or optional objects. This is kinda outdated since there is move semantics, `std::optional` and other language and starndard library improvements now. – dewaffled Dec 25 '21 at 19:38
  • It is all explained in the **Discussion** paragraph and then he show example for those cases. As written, your question is not specific enough. – Phil1970 Mar 02 '22 at 23:26

1 Answers1

1

Basically he is saying there not to put raw pointers in containers and not to use the old auto_ptr which as of C++17 has been removed from the standard library.

On your questions:

Question 1: when Sutter says "contain", does he mean "own"? like "Containers assume they own value-like types"?

Actual value types -- like int say -- do not have owners. Nothing owns 5 or 42. By "value-like" types he means types that are not exactly values but that have well-defined copying semantics so that you can pass them around as though they are values. std::shared_ptr for example is like this. It is not a value but you can pass it around like a value. Sutter does not mention move-only types here because the book predates their existence in standard C++.

Question 2: besides value types, smart pointers, and iterators, what else types can be stored? For example, reference? Why reference is not recommended to be stored in containers?

Well, now you can store move-only types in containers e.g. std::unique_ptr. you just have to honor their move semantics.

You can't store naked references in containers. The STL containers are written generically and basically storing references in them doesn't work because copying a reference does not mean what the container implementations expect it to mean, i.e. double references are not part of C++. If you want to store references in STL containers you can use std::reference_wrapper.

jwezorek
  • 8,592
  • 1
  • 29
  • 46