zoukankan      html  css  js  c++  java
  • C++ string 内存管理

    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 << "	empty: "<< empty.size()<<endl;
    	cout << "	small: "<< small.size()<<endl;
    	cout << "	large: "<< large.size()<<endl;
    
    	//重新分配内存大小
    	cout << "Capactities: 
    ";
    	cout << "	empty: "<< empty.capacity()<<endl;
    	cout << "	small: "<< small.capacity()<<endl;
    	cout << "	large: "<< large.capacity()<<endl;
    
    	//reserve方法能够请求内存块的最小长度
    	empty.reserve(50);
    	cout << "Capacity after empty.reserve(50): "
    		 << empty.capacity() << endl;
    
    	return 0;
    }
    

     

  • 相关阅读:
    盒模型(框模型)
    边框
    尺寸及溢出处理
    HTML标签分类
    尺寸单位和颜色的取值
    选择器的优先级
    C++ 代码模板
    LC 425. Word Squares 【lock,hard】
    LC 660. Remove 9 【lock, hard】
    LC 759. Employee Free Time 【lock, hard】
  • 原文地址:https://www.cnblogs.com/yutingmoran/p/10455841.html
Copyright © 2011-2022 走看看