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

相关推荐
博客180014 小时前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴15 小时前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨1 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4565 天前
C++进阶(1)——前景提要
c++
夜悊6 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴6 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0016 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾6 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you6 天前
constexpr函数
c++
凡人叶枫6 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++