哪个占用更少的内存?

问题描述 投票:-1回答:3

这两种解决方案中的哪一种占用更少的内存?

  • short X; short Y;
  • array<pair<short,short>,1> Coords;
c++ arrays memory memory-management
3个回答
2
投票

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个字节。


2
投票

short的大小取决于平台,编译器和体系结构,但假设其大小为2个字节,则两者都将占用4个字节的内存。

static_assert(sizeof(std::array<std::pair<short, short>, 1>) == sizeof(short[2]))

因此静态断言为什么不会在这里失败


0
投票

谢谢您的回答,我也意识到,而不是

array<pair<short,short>,1> Coords

您可以输入

pair<short,short> Coords

© www.soinside.com 2019 - 2024. All rights reserved.