Can I use const in vectors to allow adding elements, but not modifications to the already added?

后端 未结 14 615
既然无缘
既然无缘 2020-12-01 04:54

My comments on this answer got me thinking about the issues of constness and sorting. I played around a bit and reduced my issues to the fact that this code:



        
14条回答
  •  天命终不由人
    2020-12-01 05:31

    Compilation fails because push_back() (for instance) is basically

    underlying_array[size()] = passed_value;
    

    where both operand are T&. If T is const X that can't work.

    Having const elements seem right in principle but in practice it's unnatural, and the specifications don't say it should be supported, so it's not there. At least not in the stdlib (because then, it would be in vector).

提交回复
热议问题