【发布时间】:2016-12-22 16:21:08
【问题描述】:
我有这个 C++ 结构:
typedef unsigned long T;
struct Node {
T index;
T length;
Node(): index(0), length(0), next(0) {}
Node(const T &ind, const T &len): index(ind), length(len), next(0) {}
vector<Node*> next;
};
我正在尝试找出 next 将占用多少内存。我知道它最多有五个元素。所以这就是我要做的:
int main(int argc, const char * argv[]) {
Node n;
Node* x = new Node(3, 4);
cout << "An empty vector of pointers: " << sizeof(n.next) << " bytes\n";
// Add five elements
for(int i = 0; i < 5; i++)
n.next.push_back(x);
cout<< "New size of the vector of pointers: " << n.next.size() << " elements\n";
cout<< "New size of the vector of pointers: " << sizeof(n.next) << " bytes\n";
return 0;
}
这是我的输出:
An empty vector of pointers: 24 bytes
New size of the vector of pointers: 5 elements
New size of the vector of pointers: 24 bytes
我的问题:一个空向量怎么可能占用 24 个字节,但其中包含 5 个元素的同一个向量仍然占用 24 个字节?不应该占用更多内存吗?比如 *24 + 5 * sizeof(Node*)*?
【问题讨论】:
-
int* x = new int[1]; int* y = new int[100]。想一想,为什么sizeof(x) == sizeof(y),即使它们指向不同大小的数组? -
这两种情况都是指针的大小?
-
如果您至少需要知道向量正在使用多少内存,请使用
sizeof(n.next) + n.next.capacity() * sizeof(Node*);如果您需要确切知道向量已分配多少内存,请为向量提供您自己的分配器。
标签: c++