Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does VC++ 2010 allow this to compile?

Tags:

c++

visual-c++

std::vector<const int> vci;
vci.push_back(1);
vci[0] = 2;

With the element type being const int, shouldn't the assignment statement be assigning to a const int&? This does not compile with LLVM 3.0. Why does VC++ allow it?

like image 550
Tabber33 Avatar asked Apr 05 '12 19:04

Tabber33


1 Answers

While it is Undefined Behavior and basically anything can happen including what you are seeing, I have tracked this to what seems to be an incompatibility of the library with the standard. In particular the standard allocator defined in the VS2010 library does not conform with the standard.

The standard dictates that std::vector<T,Allocator>::value_type is a typedef to Allocator::value_type. Now the default allocator (if none is provided) is std::allocator<T> for which value_type, according to Table 28 must be Identical to T. Now the implementation of the standard allocator in VS2010 drops the const qualifier from the type argument, so std::allocator<const T>::value_type is T, and not const T.

It is important to note that the compiler is not non-conformant for accepting the code that you provided per-se, since it is Undefined Behavior and the compiler is free to do as it pleases. But on the other hand, there is a non-conformity in the std::allocator implementation.

You have already answered the question yourself: It is Undefined Behavior. The compiler does not need to provide a diagnostic, and the result of the operation can be anything. It is a case of quality of implementation to detect that the type is not assignable and provide a meaningful error message (or not)

like image 85
David Rodríguez - dribeas Avatar answered Oct 27 '22 18:10

David Rodríguez - dribeas