I have his code:
int setAttrib(const string& name, int components){
// here I don't even touch 'name'
if(components == 2) return 3;
else return 1;
}
And I call the function this way:
setAttrib("position", 3);
I'm profiling memory with xcode profiler and in the function call std::string is making an allocation.
Why is that?
EDIT:
What's the best way to avoid that allocation? since I'm calling that function a lot, and in about 10 seconds of time I end up allocating about 10MB in that line.
Thanks.
You ask for a const string&, but pass in a const char*. The compiler thus needs to create a temporary object of the correct type.
The fact that "position" is not an std::string but a char const* is more of a historical accident (inherited from C, when there was no string class in C++) than a design decision, but something to keep in mind nevertheless.
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