0

After reading this post I tried this

#include <iostream>
#include <vector>

int main()
{
    const int x = 5;
    // x = 200;           Not possible, of course.

    std::vector<const int> xVector = { 5 };
    xVector[0] = 200;

    std::cout << xVector[0];   // 200, no surprise.
}

This compiles in Visual Studio 2017. But is this behaviour undefined as in UB?

Bonus questions: What are the technical reasons that a std::vector<const int> isn't just a vector of un-modifiable ints?

TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52
  • [This question](https://stackoverflow.com/questions/13768089/vectorconst-int-is-not-allowed-why-is-pairconst-int-int-allowed) says that it's not allowed. – user202729 May 14 '18 at 14:45
  • *"This compiles in Visual Studio 2017"* - Then it's either a bug or permissive flag in your project options. – StoryTeller - Unslander Monica May 14 '18 at 14:45
  • 5
    Possible duplicate of [Does C++11 allow vector?](https://stackoverflow.com/questions/6954906/does-c11-allow-vectorconst-t) – Aimery May 14 '18 at 14:46
  • (compilers are required to compile correct code, but are not required to error (although they're expected to do so, especially with `-pedantic`) on incorrect code -- compiler specific extension is a thing) – user202729 May 14 '18 at 14:46
  • 3
    By the way. MSVC on godbolt doesn't accept it https://godbolt.org/g/Y6qmjj – StoryTeller - Unslander Monica May 14 '18 at 14:47
  • 1
    **NOT** a duplicate of the "is it allowed" question. This is more specific. The other question establishes it's not allowed, but it's either ill-formed or Undefined Behavior. Which of the two is not answered there, and asked here. – MSalters May 14 '18 at 15:35

0 Answers0