关于 C++中 sizeof 的思考

以下为试验程序:

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

int main()
{
    
    
	string word1 = "Teddy";
	string word2 = "Bear";
	vector<int> vec1{
    
     0,1,2,3,4 };
	vector<int> vec2{
    
     0,1,2 };
	vector<string> vec3 = {
    
     "Teddy","Bear" };
	cout << "size of int is " << sizeof(int) << ".\n";
	cout << "size of long is " << sizeof(long) << ".\n";
	cout << "size of long long is " << sizeof(long long) << ".\n";
	cout << "size of short is " << sizeof(short) << ".\n";
	cout << "size of char is " << sizeof(char) << ".\n";
	cout << "size of 'word1' is " << sizeof word1 << ".\n";
	cout << "size of 'word2' is " << sizeof word2 << ".\n";
	cout << "size of 'vec1' is " << sizeof vec1 << ".\n";
	cout << "size of 'vec2' is " << sizeof vec2 << ".\n";
	cout << "size of 'vec3' is " << sizeof vec3 << ".\n";
	return 0;
}

我的电脑的output为:
Output
(每台电脑不一定一样)
由规律知 vector,string 的 sizeof 值与存的内容无关
此程序中未列数组的sizeof。数组的为每个元素的sizeof值乘上个数。


【C++ Primer(5th Edition) Exercise】练习程序 - Chapter4(第四章)

猜你喜欢

转载自blog.csdn.net/weixin_50012998/article/details/108257791