> > 2) "advanced" c++ code:
> >
> > void foo(const std::string& xxx) { ... };
> > int main() { foo("bar"); }
> >
> > copy-created 2nd string is avoided, but string object to hold "bar" is still must be
> > made, 1 malloc(), 1 memcpy().
>
> Are you sure about this? I always thought that foo only receives a pointer to xxx which it puts on the stack, so
> no additional malloc/free is involved.
Yes, "bar" is not an std::string, cannot be used to call foo(), and the c++ compiler has to automagically rewrite
the function call
from: int main() { foo("bar"); }
to: int main() { foo(std::string("bar"); }
the temporary std::string object may be on the stack, but storage for text "bar" is on the heap (unless std::string
is optimized to store short strings internally).
one can put a printf() inside foo() to print the address of xxx (should be on the stack) and xxx.c_str() (should be
on the heap). one could also try to print the address of "bar" (should be in the read-only-constant-strings memory
area). (I am not sure if compiler-linker combines all instances of "bar" into one, this is also easy to check).
K.O. |