title: Why can't you put a const object into a STL container?
body: <p>See the code below - I am trying to put a const object into a vector. I know the answer is "STL containers require objects to be assignable and copy constructable", but, without citing the standard, can anyone explain what the problem with doing this is? I don't understand why a class like this could not be copied (besides that c++ doesn't allow it).</p>
  
  <p>All it is is a value stored that is not allowed to be changed - why can't putting it in a vector simply create another one of these objects?</p>
  
  <pre><code>#include &lt;vector&gt;
  
  // Attempt 1
  // /home/doriad/Test/Test.cxx:3:8: error: non-static const member ‘const int MyClass::x’, can’t use default assignment operator
  
  // struct MyClass
  // {
  //   int const x;
  //   MyClass(int x): x(x) {}
  // };
  // 
  // int main()
  // {
  //   std::vector&lt;MyClass&gt; vec;
  //   vec.push_back(MyClass(3));
  //   return 0;
  // }
  
  // Attempt 2
  // /home/doriad/Test/Test.cxx:28:23: error: assignment of read-only member ‘MyClass::x’
  struct MyClass
  {
    int const x;
    MyClass(int x): x(x) {}
    MyClass&amp; operator= (const MyClass&amp; other)
    {
      if (this != &amp;other)
      {
        this-&gt;x = other.x;
      }
  
      return *this;
    }
  };
  
  int main()
  {
    std::vector&lt;MyClass&gt; vec;
    vec.push_back(MyClass(3));
    return 0;
  }
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>It is possible to do this with std::set and std::list. I guess it is the sort() function in std::vector that uses assignment. This is not UB right?</p>
  
  <pre><code>#include &lt;set&gt;
  
  // Attempt 1
  struct MyClass
  {
    int const x;
    MyClass(int x): x(x) {}
    bool operator&lt; (const MyClass &amp;other) const;
  };
  
  bool MyClass::operator&lt;(const MyClass &amp;other) const
  {
    if(this-&gt;x &lt; other.x)
    {
      return true;
    }
    else if (other.x &lt; this-&gt;x)
    {
      return false;
    }
  
  }
  
  
  int main()
  {
    std::set&lt;MyClass&gt; container;
    container.insert(MyClass(3));
    return 0;
  }
  </code></pre>