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 = new vector<string>();
...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?
so there is no need to avoid it.
Well, there are reasons to avoid indirection when possible. But this "temporary" is not such reason since it's not true.
What is the C++ rule that avoids creating temporary object in such a case.
There just isn't a rule saying that a temporary object would be created.
will copy since *ptr_string is an rvalue in this case?
*ptr_string is an lvalue; not rvalue. (assuming decltype(ptr_string) is std::string*; it could be an rvalue for strange overloads of unary * operator for class types).
string str = ... will copy because it is copy initialising a value object.
Why is it different with the for loop?
It's not different with the for loop. You can do the copy with a loop as well:
for(string str: *vecptr)
// ^ is not a reference: therefore it is a copy of the element
As well as no copy with a "regular" variable:
string& str = *ptr_string;
// ^ is a reference: therefore not a copy
It's also entirely the same even if you hadn't indirected through pointer, but instead used some other lvalue such as a reference or the name of a variable instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With