sorted_vector, constness, pointers, and structs

Lubos Lunak l.lunak at suse.cz
Wed Jul 18 10:23:06 PDT 2012


On Wednesday 18 of July 2012, Noel Grandin wrote:
> Hi
>
> So David and Stephan recommended that I make the accessor methods to
> o3tl::sorted_vector const in order to prevent clients from invalidating
> the sorted-ness of it.
> This works out fine when I'm storing pointers to something in the
> sorted_vector like this:
>
> struct SomeStruct {
>      int xxx;
> }
> o3tl::sorted_vector<SomeStruct*>  var1;
> var1[0]->xxx = 12;
>
> Which is because thanks to C++'s typing rules, const-ness does not
> propogate with a pointer.
> However, if I do this:
>
> o3tl::sorted_vector<SomeStruct>  var1;
> var1[0].xxx = 12; // <--- error! reference is const!!!
>
> And, in fact, if I store any value class directly into
> o3tl::sorted_vector, it becomes pretty much useless, because I can't get
> anything out of it afterwards without casting away the const-ness.

 But it is correct that you get an error in the second case and you ideally 
should be getting one in the first case as well. You cannot modify the 
elements of the vector because that might modify what defines their position 
in their sorted order, isn't that so? That is exactly the reason for those 
changes as suggested by David and Stephan.

 So the problem is that most that the sorted_vector class, as designed by now, 
does not fit the purpose. If the original code really did directly modify 
elements of a sorted container, and if it's not easy to avoid, then I think 
the easiest solution would be adding something like "T& 
sorted_vector::get_element_to_modify( int index )", which would allow you do 
do what is necessary, and at the same time would make it obvious it's 
intentional. I doubt it's possible to make the compiler check that this 
really does not alter the way the element would be sorted.

> What is the "correct C++ idiom" here?

 Uhm ... not do broken things :) ?

> Should I create a separate container types here?

 Not needed, given the above. If you'd like to ensure that the first case with 
a pointer is flagged as an error as well, I think a template specialization 
should be able to handle it (I think I can do that if it's too much of voodoo 
magic for you).

-- 
 Lubos Lunak
 l.lunak at suse.cz


More information about the LibreOffice mailing list