哪个占用更少的内存?

问题描述 投票:2回答:2

我正在编程,我想知道:这两种解决方案中哪一种占用的内存更少?

  • short X; short Y;
  • array<pair<short,short>,1> Coords;

该程序用C ++编写

c++ arrays memory memory-management
2个回答
2
投票

使用代码和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个字节。


0
投票

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

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

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

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