79. Store only values and smart pointers in containers


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


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.


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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.