views:

270

answers:

3

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?

+4  A: 

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.

Charles Bailey
I guess it does pay off to use several compilers, learning curve-wise. However, I'd rather have a static analysis tool to point at such slippery assignments.
msiemeri
You might want to check out [STLport][http://www.stlport.org/]. I'll have to install it again and see if it catches this.
D.Shawley
+3  A: 

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.

anon
+1, the key point being that "template parameter must be assignable" is a constraint on the program. It's not a requirement on the compiler to tell you if it isn't.
Steve Jessop
+2  A: 

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.

dimba
I think, I understand the const/Assignable problem. I wonder, however, why VS does not provide an error message when using the accordant code in my question.
msiemeri