pass vectors by pointer and reference in c++ -



pass vectors by pointer and reference in c++ -

a quick question how safely pass , utilize vectors in c++.

i know when using vectors have careful addresses them , elements because when dynamically alter size may alter address (unless utilize reserve etc. i'm imagining not know how much space need).

now want pass existing vector (created elsewhere) function adapts , changes size etc. i'm little unclear safe because accomplish of pointers. on top of there using references vector , muddies water me.

for instance take 2 next functions , comments in them

void function1(std::vector<int>* vec){ std::cout<<"the size of vector is: "<<vec->size()<<std::endl; //presumably valid here (int i=0;i<10;i++){ (*vec).pushback(i); //is safe? or fail? // or: vec->pushback(i); difference? } std::cout<<"the size of vector is: "<<vec->size()<<std::endl; //is line valid here?? }

and

void function2(std::vector<int>& vec){ std::cout<<"the size of vector is: "<<vec.size()<<std::endl; //presumably valid here (int i=0;i<10;i++){ vec.pushback(i); //is safe? or fail? } std::cout<<"the size of vector is: "<<vec.size()<<std::endl; //is line valid here?? }

is there difference between 2 functions, both in terms of functionality , in terms of safety?

or in other words, if have pointer/reference vector , need resize how can sure vector in memory, or pointer vector is, after operate on it. thanks.

in term of functionality, in limited context gave us, same.

in more general view, if want write generic code, consider operation , operators bind straight reference, not pointers

a = b + c;

to compile requires

a operator+(const b&, const c&);

but

a* operator+(const b*, const c*);

is different beast.

also, look taking reference , taking value have same syntax, look taking pointers require pointers deference provide equal semantics, leads different look syntax ( *a + *b against a+b ) leading "less general code".

on counterpart, if writing class have runtime polymorphism (and lyskov substitution in mind), treat dynamically allocated object, , hence, manipulating them through pointers may more natural.

there "grey areas" 2 things mesh, -in general- pointer taking function more frequent in runtime based oop frameworks, while reference taking functions more frequent in "value based generic algorithms", static type deduction expected, , on-stack based allocation wanted.

c++ pointers vector

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -