非POD类型的`std :: realloc` [英] `std::realloc` for non-POD types

查看:59
本文介绍了非POD类型的`std :: realloc`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对非POD类型使用 std :: realloc 是否安全?

Is it safe to use std::realloc for non-POD types?

例如,如果我 realloc 一个STL容器数组,即使内容被移动也不会有问题,因为容器对象的所有成员(包括指向实际数据的指针)都是还在那儿.为每个元素调用复制构造函数不是一种浪费,它可以分配新的堆内存并复制所有内容,然后释放所有旧的内存块.例如,考虑调整 std :: vector< std :: vector< int>> 的大小.

If I realloc an array of STL containers for example, it won't be a problem even when the contents are moved because all the members of the container objects including the pointers to the actual data are still there. Isn't it kind of a waste to call the copy constructors for each element, which can possibly allocate new heap memory and copy all the contents, and then deallocate all of the old memory blocks. Think about resizing a std::vector<std::vector<int>> for example.

我想念什么吗?

注意:当然,您很少会在C ++中调用 realloc ,但是请考虑在设计涉及调整大小的数据结构的类时.

Note: Of course you'll rarely call realloc in C++, but think about when you're designing a class of a data structure that involves resizing.

推荐答案

当要求 realloc 扩展分配的区域时,它可以通过两种不同的方式成功:

When realloc is asked to extend an allocated area it can succeed in two different ways:

  • realloc 可以以某种方式扩展区域,因此保留其地址,但会变大.只要将新零件视为未初始化的存储,就没有问题.

  • realloc can somehow extend the area, so it keeps its address but gets larger. This is unproblematic as long as the new part is treated as uninitialized storage.

realloc 可以分配合适的新区域,复制数据,并取消分配原始区域.问题1 :复制并不总是适用于负责复制或移动的类型.问题2:指向原始区域中对象的指针和引用现在无效.

realloc can allocate a suitable new area, copy the data over, and deallocate the original area. Problem 1: the copying is not always appropriate for a type that takes charge of copying or moving. Problem 2: Pointers and references to objects in the original area, are now invalid.

很容易想到对非POD项目适用的情况,也很容易想到不适用于POD项目的情况.对于不工作的情况,最简单的可能是链接结构的 Node 类型,其中节点之间具有相互的指针.

It's easy to think of cases where it will work for a non-POD items, and it's also easy to think of cases where it will not work. Perhaps easiest for not-work, a Node type for a linked structure, where the nodes have pointers to each other.

结果是可以真正提高速度(例如CPython使用 realloc 进行字符串处理),但是 std :: vector 过于笼统利用这一点.一个需要一些更专用的自定义容器.AFAIK在Boost中没有这样的功能,但是即使我没有听说过,也可能只是这样.

The upshot is that one can get a real speed improvement (e.g. CPython uses realloc for its string handling), but std::vector is too general a beast to make use of this. One needs some more dedicated custom container. AFAIK there's no such in Boost, but there might just be even if I haven't heard of it.

这篇关于非POD类型的`std :: realloc`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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