当我们使用string类时,通常会堆内存的分配:
#include <iostream>
#include <string>
using namespace std;
void* operator new(size_t count)
{
cout << "new " << count << " bytes" << endl;
return malloc(count);
}
int main()
{
cout<<"init s1"<<endl;
string s1 = "123456789";
cout<<"init s2"<<endl;
string s2 = "abcdefghijklmnopqrstuvwxyz";
cout<<"init s3"<<endl;
string&& s3 = s2.substr(5);
return 0;
}
运行程序输出:
init s1
init s2
new 27 bytes
init s3
new 22 bytes
可见,当使用string时有时是在堆上分配的内存,有时却不是。
这个是根据字符串的长度来决定的,当字符串的长度(含结束符)小于等于16时,字符串实际上被