C ++中连续内存的意义是什么? [英] What is the meaning of contiguous memory in C++?

查看:562
本文介绍了C ++中连续内存的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++中连续内存的含义是什么?

What is the meaning of contiguous memory in C++?

推荐答案

这意味着内存被分配为单个块。

It means that memory is allocated as a single chunk. This is most often used when talking about containers.

例如,向量 string 类使用连续的内存块。这意味着如果你有一个包含 int 元素 123 456 789 ,那么你可以放心,如果你获得指向vector的第一个元素的指针,通过增加这个指针,你将访问第二个元素(456),并再次递增它,你将访问最后一个元素(789)。

For instance, the vector and string classes use a contiguous chunk of memory. This means that if you have a vector that contains the int elements 123, 456, 789, then you can be assured that if you get the pointer to the first element of the vector, by incrementing this pointer, you'll access the second element (456), and by incrementing it again you'll access the last element (789).

std::vector<int> vec = {123, 456, 789};

int* ptr = &vec[0];
*ptr++ == 132; // true
*ptr++ == 456; // true
*ptr++ == 789; // true

另一方面,deque类不保证连续的存储。这意味着如果您拥有包含相同元素(123,456,789)的deque,并且您获得了指向第一个元素的指针,您不能确定您将访问第二个

The deque class, on the other hand, does not guarantee contiguous storage. This means that if you have a deque that contains the same elements (123, 456, 789), and that you get a pointer to the first element, you cannot be certain that you'll access the second element by incrementing the pointer, or the third by incrementing it again.

std::deque<int> deque = {123, 456, 789};

int* ptr = &deque[0];
*ptr++ == 132; // true
*ptr++ == 456; // not necessarily true and potentially dangerous
*ptr++ == 789; // not necessarily true and potentially dangerous

另一个非连续数据结构的例子是链接列表。使用链接列表,几乎不可想象,增加头指针可以返回第二个元素。

Another example of a non-contiguous data structure would be the linked list. With a linked list, it's almost unthinkable that incrementing the head pointer could return the second element.

这很少相关,假设你使用C ++好的做法,的指针尽可能多,因为它让集合管理他们如何存储他们的项目,而不必担心他们如何做。通常,如果你必须从C ++代码调用C代码,那么你需要内存是连续的,因为大多数C函数都设计为使用连续内存,因为这是最简单的方法。

It is rarely relevant, assuming you use C++ good practices such as using iterators instead of pointers as much as you can, because it lets collections manage how they store their items without having to worry about how they do it. Usually, you'll need memory to be contiguous if you have to call C code from your C++ code, as most C functions were designed to work with contiguous memory because that's the simplest way to do it.

这篇关于C ++中连续内存的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆