Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Why is memory allocated when passing a string literal to a function?

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.

like image 219
Damian Avatar asked Nov 29 '22 10:11

Damian


1 Answers

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.

like image 117
Christopher Creutzig Avatar answered Jan 18 '23 23:01

Christopher Creutzig