mardi 17 mars 2020

Dereferencing in for loop

Apparently I've had wrong assumption that dereferencing a pointer will always create a temporary object. For ex., in the following piece of code

vector<string> *vecptr;
...populate vector...
for(string& str: *vecptr)
{ //do something }

I've always thought *vecptr would create a local temporary object and inefficient. I was averse to dereference in the loop and would do something like

for(vector<string>::iterator str = vecptr->begin(); ....

for the sake of avoiding dereferencing. I just learned that dereferencing does not create a temporary object in the first case, so there is no need to avoid it. What is the C++ rule that avoids creating temporary object in such a case. Under a regular case

string str = *ptr_string;

will copy since *ptr_string is an rvalue in this case? Why is it different with the for loop?

Aucun commentaire:

Enregistrer un commentaire