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():字符串有多长

相关推荐
会编程的小孩40 分钟前
C++ qt的安装
c++
小成202303202656 小时前
C++~07补充
开发语言·c++
hold?fish:palm6 小时前
40 二叉树的直径
c++·leetcode
解决小子7 小时前
【虚幻引擎】【C++】【GAS框架】构建角色基类、属性集、数值钳制
c++·笔记·游戏引擎·虚幻·gas·能力系统
lunar_coder8 小时前
【C++】如何解决智能指针的析构函数,如何实现shared_ptr的引用计数以及解决shared_ptr的循环引用
c++·1024程序员节
白白白小纯9 小时前
C++进阶.多态
c++
凯瑟琳.奥古斯特10 小时前
力扣1016高效解法:剪枝优化技巧
开发语言·c++·算法·leetcode·职场和发展
xiangyun6110 小时前
C++ priority_queue 底层:手撕二叉堆与 Top K 问题
c++·算法·面试·stl·1024程序员节
坤坤子吖10 小时前
C++继承:友元、静态成员、多继承与组合
开发语言·c++·笔记·学习·1024程序员节
qz_Serene11 小时前
练习算法题:双指针 -cpp
c++·算法·leetcode·1024程序员节