C++字符串对象有无使用字符串池?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
class student{
public:
int id;
char *name;
string address;
void say(){
cout<<"Hello world!"<<endl;
}


};
int main()
{
printf("C字符指针-字符串池\n");
int a=10;//显然在栈中,用于判断c1、c2在栈还是堆
const char *c1="abc";
const char *c2="abc";
char *c3=(char*)malloc(4);//显然堆中
strcpy(c3, "abc");//若c3="abc",则意味着字符串池中的地址覆盖申请的堆地址,后面free(c3)报错,因c3指向字符串池中的地址无法释放
int *p=(int*)malloc(sizeof(int));//显然堆中
*p=10;
printf("c1:%s\nc2:%s\nc3:%s(堆)\n*p:%d(堆)\n",c1,c2,c3,*p);
printf("c1=%p(字符串池中)\nc2=%p(字符串池中)\nc3=%p(堆)\n p=%p(堆)\n",c1,c2,c3,p);//值相等,即指向同一块内容空间
printf("&a =%p(栈)\n&c1=%p\n&c2=%p\n&c3=%p\n&p =%p\n",&a,&c1,&c2,&c3,&p);//c1,c2占8个字节,连续,分配地址高到低差8

printf("C++字符串-无字符串池\n");
string s1="abc";
string s2="abc";
int *hp=new int;//显然hp在栈中,其值是在堆中开辟的一个整型变量地址,用于查判断“abc”地址是栈、堆还是字符串池中
*hp=100;
printf("s1:%s\ns2:%s\n*hp:%d\n",s1.data(),s2.data(),*hp);
printf("s1=%p(?)\ns2=%p(?)\np =%p(堆)\n",(void*)s1.c_str(),(void*)s2.c_str(),hp);
printf("&s1=%p\n&s2=%p\n &hp=%p\n",&s1,&s2,&hp);
printf("s1所占空间的大小:%d(不是“abc”字符串长 3+1 B),整型指针hp:%d\n",sizeof(s1),sizeof(hp));
printf("可以推出“string类在底层实际上就是一个字符指针”网上有这么介绍。\n");
printf("s1[0]:%c s1[1]:%c s1[2]:%c\n",s1[0],s1[1],s1[2]);
s1[0]='c';
printf("s1[0]:%c\n",s1[0]);
printf("s1[0]的值可以修改,说明s1指向的字符串不在字符串池中(不可修改),在堆中.\n ");
printf("字符串类对象变量s1是一个指向堆中一个字符串类对象的(特殊)字符指针.\n ");
free(c3);
free(p);
delete hp;

student s;
cout<<"学生类对象栈空间大小"<<sizeof(s)<<endl;
printf("&s=%p\n",&s);
printf("说明类的对象在栈中开辟空间,另类中的方法不在栈中开辟空间,\n之所以为24,类似结构体成员\"对齐技术\",指针宽8,3*8.再加一个int,是4*8=32,再加一个还是4*8=32.\n");
return 0;
}

posted @ 2026-04-04 16:55  师大无雨  阅读(5)  评论(0)    收藏  举报