这两种解决方案中的哪一种占用更少的内存?
short X; short Y;
array<pair<short,short>,1> Coords;
在C++2a(GNU)
编译器中使用以下代码:
#include <array>
#include <iostream>
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]))
因此静态断言为什么不会在这里失败
谢谢您的回答,我也意识到,而不是
array<pair<short,short>,1> Coords
您可以输入
pair<short,short> Coords