Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which vector address is safer?

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?
like image 359
huseyin tugrul buyukisik Avatar asked Dec 02 '22 10:12

huseyin tugrul buyukisik


1 Answers

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.

like image 176
Maxim Egorushkin Avatar answered Dec 04 '22 01:12

Maxim Egorushkin