Dereference vector pointer to access element

前端 未结 2 1315
半阙折子戏
半阙折子戏 2020-12-12 15:07

If i have in C++ a pointer to a vector:

vector* vecPtr;

And i\'d like to access an element of the vector, then i can do this by

2条回答
  •  醉酒成梦
    2020-12-12 15:35

    No, nothing will be copied; dereferencing just tells C++ that you want to invoke operator[] on the vector, not on your pointer, vecPtr. If you didn't dereference, C++ would try to look for an operator[] defined on the std::vector* type.

    This can get really confusing, since operator[] is defined for all pointer types, but it amounts to offsetting the pointer as though it pointed to an array of vector. If you'd really only allocated a single vector there, then for any index other than 0, the expression evaluates to a reference to garbage, so you'll get either a segfault or something you did not expect.

    In general, accessing vectors through a pointer is a pain, and the (*vecPtr)[index] syntax is awkward (but better than vecPtr->operator[](index)). Instead, you can use:

    vecPtr->at(index)
    

    This actually checks ranges, unlike operator[], so if you don't want to pay the price for checking if index is in bounds, you're stuck with (*vecPtr)[].

提交回复
热议问题