c ++中新分配的int的内存大小,是否有不同的更好的方式来查看它?

All*_*son 2 c++ memory size allocation

#include "stdafx.h"
#include <iostream>
#include <new>

int main(){

const int gib = 268435256; //Created a constant int so i could allocate 1 
                           //Gib memory
int *ptr = new int [gib];

std::cout << sizeof (int)*gib << std::endl;
std::cout << *ptr << std::endl;
std::cout << ptr << std::endl;

try {


}catch (std::bad_alloc e) {
    std::cerr << e.what() << std::endl;
}

system("PAUSE");
delete[] ptr;

return 0;


}
Run Code Online (Sandbox Code Playgroud)

在这个程序中,我试图找出为我的指针分配了多少内存,我可以通过这种方式看到它应该是1 gibibyte wich = 1 073 741 824字节.我的问题是,我可以得到这个的唯一方法是取int的大小为4并乘以该const数.有不同的方式吗?

Chr*_*ckl 6

不,没有办法.编译器在内部添加有关分配了多少内存以及创建了多少元素的信息new[],因为否则无法delete[]正确执行.但是,C++中没有可移植的方法来获取该信息并直接使用它.

因此,您必须在您仍然知道的情况下单独存储尺寸.

实际上,你没有,因为std::vector它适合你:

#include <iostream>
#include <vector>
#include <new>

int main() {

    const int gib = 268435256;

    try {
        std::vector<int> v(gib);
        std::cout << (v.capacity() * sizeof(int)) << '\n';
    } catch (std::bad_alloc const& e) {
        std::cerr << e.what() << '\n';
    }
}
Run Code Online (Sandbox Code Playgroud)

你几乎不应该使用new[].使用std::vector.


请注意,我已经使用过,capacity而不是size,因为它size告诉你向量表示了多少项,并且该数字可以小于向量当前分配的内存所支持的元素数.

也没有办法避免sizeof,因为a的大小int可能因实现而异.但这也不是问题,因为a std::vector不能丢失它的类型信息,所以你总是知道一个元素有多大.

如果是a std::vector<char>,a std::vector<unsigned char>或a std::vector<signed char>,则不需要乘法,因为这三种字符类型' sizeof保证为1.