Which vector address is safer?

  • A+

Assuming a function needs a pointer to a vector of type T but when I have only a vector of vector of type T(type is not guaranteed to be a POD), is this

std::vector<std::vector<T>> input; auto selectedVectorPtr=&input[j]; 

safer than this

std::vector<std::vector<T>> input; auto selectedVectorPtr=&(input[j]); 

also assuming input's scope doesn't end until that function which takes selectedVectorPtr as parameter.

My concerns(/misconceptions) are:

  • does () create any temporary object? So is taking address of it is bad?
  • does operator overloading of & or [] on type T have any effect on changing priority of operator precedence?
  • what if vector(or both) is resized after getting address?


operator[] has higher precedence then operator& (postfix operators have the highest precedence), so it is evaluated first here, no parenthesis needed. There is no difference between &input[j] and &(input[j]) here.

Alternative simpler syntax:

auto selectedVectorPtr = input.data() + j; 

No need for std::addressof here either.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: