Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constness of STL containers and their elements - when to use const?

I have been overthinking (some may say underthinking, let's see what happens) the const-ness of STL containers and their elements.

I have been looking for a discussion of this, but the results have been surprisingly sparse. So I'm not necessarily looking for a definite answer here, I'd be just as happy with a discussion that gets the gears in my head moving again.

Let's say I have a class that keeps std::strings in a std::vector. My class is a dictionary that reads words from a dictionary file. They will never be changed. So it seems prudent to declare it as

std::vector<const std::string> m_myStrings;

However, I've read scattered comments that you shouldn't use const elements in a std::vector, since the elements need to be assignable.

Question:

  • Are there cases when const elements are used in std::vector (excluding hacks etc)?

  • Are const elements used in other containers? If so, which ones, and when?

I'm primarily talking about value types as elements here, not pointers.

like image 538
Leander Avatar asked May 14 '15 09:05

Leander


People also ask

How are STL containers implemented in C++?

They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference objects with similar properties to pointers).

What do all STL containers define?

An STL container is a collection of objects of the same type (the elements). Container owns the elements. Creation and destruction is controlled by the container.


2 Answers

My class is a dictionary that reads words from a dictionary file. They will never be changed.

Encapsulation can help here.

Have your class keep a vector<string>, but make it private. Then add an accessor to your class that returns a const vector<string> &, and make the callers go through that.

The callers cannot change the vector, and operator [] on the vector will hand them const string &, which is exactly what you want.

like image 109
Marshall Clow Avatar answered Nov 14 '22 22:11

Marshall Clow


No, for the reason you state.

like image 41
Lightness Races in Orbit Avatar answered Nov 14 '22 22:11

Lightness Races in Orbit