为什么std :: vector没有释放方法? [英] Why std::vector does not have a release method?

查看:76
本文介绍了为什么std :: vector没有释放方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己处于一种情况,我想为 std :: vector<>使用 unique_ptr release()类似物..例如:

I found myself in a situation where I would have liked to have an analog of unique_ptr's release() for std::vector<>. E.g.:

std::vector<int> v(SOME_SIZE);

//.. performing operations on v

int* data = v.release(); // v.size() is now 0 and the ownership of the internal array is released
functionUsingAndInternallyDeletingRowPointer(data);

为什么没有提供这种可能性的特定原因?可能会对 std :: vector 的内部实现施加一些约束吗?

Is there a particular reason why this kind of possibility is not provided? May that impose some constraint on std::vector's the internal implementation?

或者有一种方法让我尴尬地错过了?

Or there is a way to achieve this that I am embarrassingly missing?

推荐答案

这可能会对std :: vector的内部实现施加一些约束吗?

May that impose some constraint on std::vector's the internal implementation?

以下是一些与之冲突的例子:

Here are some examples of things that allowing this would conflict with:

  • 除非有特殊情况,否则 new T [] 无法获得基础内存分配 ,也不会被 delete [] 破坏,因为这些会在已分配但实际上不应包含任何 T 类型的对象的内存上调用构造函数和析构函数.
  • 数组的开头实际上可能不是内存分配的开头;例如向量可以在数组开始之前存储簿记信息
  • vector 在销毁时实际上可能不会释放内存;例如取而代之的是,分配可能来自实现目的用于快速创建和销毁小向量的小数组池.(此外,这些数组都可能只是更大数组的切片)
  • Barring special cases, the underlying memory allocation cannot be obtained by new T[], nor destroyed by delete[], since these would call constructors and destructors on memory that that is allocated but should not actually contain any objects of type T.
  • The beginning of the array might not actually be the beginning of the memory allocation; e.g. the vector could store bookkeeping information just before the start of the array
  • vector might not actually free the memory when destroyed; e.g. instead the allocation might come from a pool of small arrays that the implementation uses for quickly creating and destroying small vectors. (furthermore, these arrays might all just be slices of a larger array)

这篇关于为什么std :: vector没有释放方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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