const vector implies const elements?

后端 未结 4 949
难免孤独
难免孤独 2021-02-05 00:11
4条回答
  •  孤独总比滥情好
    2021-02-05 00:47

    Yes, because std::vector is a value-type rather than a reference type.

    To simplify things: An std::vector considers the values in its buffer as part of itself, so that changing them means changing the vector. This may be confusing if we only think of a vector as holding a pointer to an allocated buffer and the size: We don't change these two fields when we change elements in the buffer.

    It's the opposite than for pointers, which are reference-types; if you change the pointed-to value you haven't changed the pointer itself.

    The fact that std::vector is a value-type is a design choice - it's not something inherent in the C++ language. Thus, for example, the std::span class is also basically a pair of a pointer and a size, but an std::span can be const while you can still change the pointed-to elements. (There are other differences between spans and vectors.)

提交回复
热议问题