开发者

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开发者_StackOverflow 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.


Because std::string typically allocates heap memory to hold the string. In this case, a std::string is implicitly constructed from a string literal (which by itself resides in static storage). Some string implementations use a small buffer to serve small strings, but this doesn't seem to be the case here and is implementation-dependent anyway.

It doesn't matter that name is not used - basically, setAttrib("position", 3) is shorthand for setAttrib(std::string("position"), 3);, so when control enters setAttrib, the memory has already been allocated (of course, in your isolated code sample it would be possible for a compiler to inline getAttrib and then drop the string construction at all, but this is a compiler optimization, not a language feature).

Note that temporary objects created during function invocation are automatically destructed when the function returns, so there is no memory leaked.


In order to call the function the compiler needs to construct all parameters, const string& name included, the only way to do that in your case (you pass a string literal instead) is to construct a temporary std::string and this requires a heap memory allocation in most implementations. It doesn't matter if you use the value inside the function or not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜