我正在编程,我想知道:这两种解决方案中哪一种占用的内存更少?
short X; short Y;
array<pair<short,short>,1> Coords;
该程序用C ++编写
使用代码和C++2a(GNU)
编译器:
#include<iostream>
#include <array>
using namespace std;
int main(){
short X;
array<pair<short,short>,1> Coords;
cout << sizeof(X) << endl;
cout << sizeof(Coords) << endl;
}
似乎是同一回事,1 short
是2个字节,array
是4个字节。
如果我们尝试同样大小的地址:
cout << sizeof(&X) << endl;
cout << sizeof(&Coords) << endl;
每个8个字节。
short
的大小取决于平台,编译器和体系结构,但假设其大小为2个字节,则两者都将占用4个字节的内存。
static_assert(sizeof(std::array<std::pair<short, short>, 1>) == sizeof(short[2]))
因此静态断言为什么不会在这里失败