Question

Hello fellow C++ programmers. I have, what I hope to be, a quick question about STL containers:

std::list<std::string> l;

This statement compiles fine when used in some C++ sourcefile (with the appropriate includes). But

std::list<const std::string> m;

or

std::list<std::string * const> n;

fails to compile when using gcc (gcc version 4.0.1 (Apple Inc. build 5484)). However, using the Visual Studio 2008 C++ compiler, no complaints arise.

A little research unearths that elements in STL containers have to be Assignable. Is there a STL bug in the VC implementation (I'd say: 'unlikely') or do they use another concept of Assignable?

Was it helpful?

Solution

Technically, container elements do have to be assignable, however in std::list, list nodes are very rarely moved around, so once constructed they don't need to be copied (OK) or assigned (would cause an error).

Unless a compiler goes out of its way to test assignability, it's likely that instantiating many list operations won't actually cause a compile error, even if it's not technically legal.

OTHER TIPS

The things in a container must be assignable (i.e. not const), but the compiler does not have to instantiate all template methods unless they are actually used, at which point it can discover the const problem. Some compilers are better at doing this than others.

STL by design handles data types supporting value type semantic (copy c-tor and operator =). The problem is const, which make the contained values not support value type semantic.

For example:

std::list<const std::string> m;

fails since you can not assign value to an element of the list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top