79. Store only values and smart pointers in containers

Summary

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

Discussion

The most common use of containers is to store values held directly (e.g., vector<int>, set<string>). For containers of pointers: If the container owns the pointed-to objects, prefer a container of reference-counted smart pointers (e.g., list<shared_ptr<Widget> >); otherwise, a container of raw pointers (e.g., list<Widget*>) or of other pointer-like values such as iterators (e.g., list< vector<Widget>::iterator >) is fine.

Examples

Example 1:auto_ptr. Objects of auto_ptr<T> are not value-like because of their transfer-of-ownership ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.