c++, sizeof(string)和string.size()有什么区别

在C++中,sizeof(string)string.size()是两个完全不同的概念:

1. sizeof(string)

  • 返回的是 string对象本身在内存中占用的字节数(编译时确定)

  • 这与字符串的长度无关,而是与string类的实现有关

  • 不同编译器/标准库实现可能有不同的大小

  • 是编译时运算符,不是函数

2. string.size() (或string.length()

  • 返回的是 字符串的实际字符个数(不包括结尾的空字符)

  • 是运行时确定的

  • 是string类的成员函数

示例对比

复制代码
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1 = "hello";
    string s2 = "hello world, this is a longer string";
    
    cout << "sizeof(string): " << sizeof(string) << endl;  // 通常是24, 32等
    cout << "s1.size(): " << s1.size() << endl;           // 输出5
    cout << "s2.size(): " << s2.size() << endl;           // 输出较长字符串的长度
    
    cout << "sizeof(s1): " << sizeof(s1) << endl;        // 和sizeof(string)相同
    return 0;
}

常见误解

复制代码
string str = "test";
char arr[] = "test";

// 正确用法:
cout << str.size();        // 输出4
cout << sizeof(arr);       // 输出5(包含'\0')

// 错误用法:
// cout << sizeof(str);    // ❌ 这不是字符串长度!

总结

特性 sizeof(string) string.size()
作用 对象内存大小 字符串字符数
时机 编译时 运行时
单位 字节 字符个数
与内容关系 无关 直接相关
是否可变 固定(对特定实现) 动态变化

简单记法

  • sizeof(string)对象有多大

  • string.size()字符串有多长

相关推荐
码农-阿杰5 小时前
深入理解 synchronized 底层实现:从 HotSpot C++ 源码看对象锁与 Monitor 机制
开发语言·c++·
Szime6 小时前
深智微IC华润微代理:MCU选型与工业控制方案推荐
c++
叼烟扛炮6 小时前
C++ 知识点18 内部类
开发语言·c++·算法·内部类
汉克老师6 小时前
GESP5级C++考试语法知识(十五、分治算法(二))
c++·算法·排序算法·分治算法·gesp5级·gesp五级
汉克老师7 小时前
GESP6级C++考试语法知识(五、格雷码)
c++·算法·位运算·异或·gesp6级·gesp六级·格雷码
程序leo源8 小时前
C语言知识总结
c语言·开发语言·c++·经验分享·笔记·青少年编程·c#
沫璃染墨8 小时前
二叉搜索树完全指南:从核心原理到增删查改全实现
开发语言·c++
‎ദ്ദിᵔ.˛.ᵔ₎8 小时前
C++哈希表
数据结构·c++·散列表
想学会c++9 小时前
单例模式笔记总结
c++·笔记·单例模式
阿旭超级学得完9 小时前
C++11(初始化)
java·开发语言·数据结构·c++·算法