const vector implies const elements?

后端 未结 4 945
难免孤独
难免孤独 2021-02-05 00:11
4条回答
  •  醉梦人生
    2021-02-05 00:35

    The first version

    v[0].set (1234); 
    

    does not compile because it tries to change the vector's first element returned to it by reference. The compiler thinks it's a change because set(int) is not marked const.

    The second version, on the other hand, only reads from the vector

    (*v[0]).set(1234);
    

    and calls set on the result of the dereference of a constant reference to a pointer that it gets back.

    When you call v[0] on a const vector, you get back a const reference to A. When element type is a pointer, calling set on it is OK. You could change the second example to

    v[0]->set(1234);
    

    and get the same result as before. This is because you get a reference to a pointer that is constant, but the item pointed to by that pointer is not constant.

提交回复
热议问题