首页 > 编程语言 > 详细

C++ string 内存管理

时间:2019-03-01 13:40:19      阅读:185      评论:0      收藏:0      [点我收藏+]

String 是STL里面的类似一个字符串容器。

String对象调用append(),不能之家已有的字符串加大,因为相邻的内存可能被占用,因此需要分配一个新的内存块,将原来的内存赋值到新的内存块中。这样会降低效率。

所以c++实现分配了一个比实际字符串大的内存块,如果字符串不断增大,超过了内存块大小,程序将分配一个大小为原理两倍的新内存卡,以提高足够的空间。

 

#include <iostream>
#include <string>

int main()
{
	using namespace std;

	string empty;
	string small = "bit";
	string large = "Elephants are a girl‘s best friend";

	cout << "Sizes:"<<endl;
	cout << "\tempty: "<< empty.size()<<endl;
	cout << "\tsmall: "<< small.size()<<endl;
	cout << "\tlarge: "<< large.size()<<endl;

	//重新分配内存大小
	cout << "Capactities: \n";
	cout << "\tempty: "<< empty.capacity()<<endl;
	cout << "\tsmall: "<< small.capacity()<<endl;
	cout << "\tlarge: "<< large.capacity()<<endl;

	//reserve方法能够请求内存块的最小长度
	empty.reserve(50);
	cout << "Capacity after empty.reserve(50): "
		 << empty.capacity() << endl;

	return 0;
}

 技术分享图片

C++ string 内存管理

原文:https://www.cnblogs.com/yutingmoran/p/10455841.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!