sizeof(std::string)的大小

190 阅读1分钟

先上代码,这段代码在两个地方跑出不一样的结果。

#include <iostream>
#include <string>
using namespace std;

struct A {
	std::string str;
};

int main()
{
	std::string str;
	std::cout << "sizeof: " << sizeof(str) << "\n";
	std::string str2 = "";
	std::cout << "sizeof2:" << sizeof(str2) << "\n";
	std::string str3 = "helloworld";
	std::cout << "sizeof3:" << sizeof(str3) << "\n";
	char* pch;
	std::cout << "sizeof pch: " << sizeof(pch) << "\n";
	double* pdb;
	std::cout << "sizeof pdb: " << sizeof(pdb) << "\n";
	int* pint;
	std::cout << "sizeof pint: " << sizeof(pint) << "\n";
	std::cout << "sizeof struct:" << sizeof(A) << "\n";
	return 0;
}

自己本机:

Debug模式: image.png

release模式:

image.png

这个可以用优化来解释,但是为什么sizeof(std::string)的大小是32。

一般来说,一个类实例的大小,是这个类的成员变量的大小。

比如:

class B {
public:
	B() = default;
	~B() = default;

	size_t a[10];
};

其中sizeof(B)的大小就是80 = 10 * sizeof(size_t),符合直觉。

但是当给这个类添加一个static 变量。

class B {
public:
	B() = default;
	~B() = default;

	size_t a[10];
	static size_t b;
};

得到的sizeof(B)仍旧是80。

现在已知static变量不影响class的大小。

好吧,xstring里面的basic_string 实在看花眼了,没找到这32字节到底是哪些变量。