O'Reilly logo

C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Andrei Alexandrescu, Herb Sutter

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required