Dam*_*ian 4 c++ string memory-management
我有他的代码:
int setAttrib(const string& name, int components){
// here I don't even touch 'name'
if(components == 2) return 3;
else return 1;
}
Run Code Online (Sandbox Code Playgroud)
我用这种方式调用函数:
setAttrib("position", 3);
Run Code Online (Sandbox Code Playgroud)
我正在使用xcode profiler分析内存,并且在函数调用中,std :: string正在进行分配.
这是为什么?
编辑:
避免这种分配的最佳方法是什么?因为我调用该函数很多,并在约10秒的时间,我结束了对分配在该行10MB.
谢谢.
Chr*_*zig 13
你要求一个const string&,但通过一个const char*.因此,编译器需要创建正确类型的临时对象.
那事实"position"是不是std::string但char const*更多的是一种历史的偶然的(由C继承的,当时没有string用C++类),比设计决定的事,但要记住不过.
因为std::string通常会分配堆内存来保存字符串.在这种情况下,a std::string是从字符串文字(它本身驻留在静态存储中)隐式构造的.一些字符串实现使用一个小缓冲区来提供小字符串,但这似乎不是这里的情况,并且无论如何都依赖于实现.
没用也没关系name- 基本上setAttrib("position", 3)是简写setAttrib(std::string("position"), 3);,所以当控制进入时setAttrib,内存已经被分配(当然,在你的隔离代码示例中,编译器可以内联getAttrib然后删除字符串构建根本,但这是编译器优化,而不是语言功能).
请注意,函数调用期间创建的临时对象会在函数返回时自动销毁,因此不会泄漏内存.
为了调用该函数,编译器需要构造包括在内的所有参数,const string& name这种情况下的唯一方法(而是传递字符串文字)是构造一个临时的std::string,这在大多数实现中都需要分配堆内存。是否使用函数内部的值都没有关系。