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 aconst char*. The compiler thus needs to create a temporary object of the correct type.The fact that
"position"is not anstd::stringbut achar const*is more of a historical accident (inherited from C, when there was nostringclass in C++) than a design decision, but something to keep in mind nevertheless.