销毁std :: vector而不释放内存 [英] Destroy std::vector without releasing memory

查看:333
本文介绍了销毁std :: vector而不释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数来获取std向量中的数据:

Lets say I have a function to get data into an std vector:

void getData(std::vector<int> &toBeFilled) {
  // Push data into "toBeFilled"
}

现在我想发送这个数据到另一个函数,应该释放数据完成后:

Now I want to send this data to another function, that should free the data when finished:

void useData(int* data)
{
  // Do something with the data...
  delete[] data;
}

两个函数(getData和useData)都是固定的,不能更改。这在复制数据一次时工作正常:

Both functions (getData and useData) are fixed and cannot be changed. This works fine when copying the data once:

{
  std::vector<int> data;
  getData(data);
  int *heapData = new int[data.size()];
  memcpy(heapData, data.data(), data.size()*sizeof(int));
  useData(heapData);
  data.clear();
}

然而,这个memcpy操作是昂贵的,并不是真正需要,已经在堆上。是否可以直接提取和使用由std向量分配的数据?类似于(伪代码):

However, this memcpy operation is expensive and not really required, since the data is already on the heap. Is it possible to directly extract and use the data allocated by the std vector? Something like (pseudocode):

{
  std::vector<int> data;
  getData(data);
  useData(data.data());
  data.clearNoDelete();
}

编辑

这个例子可能没有太大的意义,因为它可以在调用useData函数后释放向量。但是,在实际代码中,useData不是一个函数,而是一个接收数据的类,并且这个类的运行时间比向量长。

The example maybe doesn't make too much sense, since it is possible to just free the vector after the function call to useData. However, in the real code, useData is not a function but a class that receives the data, and this class lives longer than the vector...

推荐答案

否。

您使用的API有一份合同,声明它需要您提供的数据的所有权,并且该数据通过指针提供。这基本上排除了使用标准向量。

The API you're using has a contract that states it takes ownership of the data you provide it, and that this data is provided through a pointer. This basically rules out using standard vectors.

向量将总是确保释放它分配的内存,并安全地销毁它包含的元素。

Vector will always assuredly free the memory it allocated and safely destroy the elements it contains. That is part of its guaranteed contract and you cannot turn that off.

您如果您想要取得资料的副本,请拥有权...或将 每个元素移出到您自己的容器中。或者首先使用自己的 new [] (ugh),虽然你至少可以在类中模仿 std ::向量并成为非所有者。

You have to make a copy of the data if you wish to take ownership of them... or move each element out into your own container. Or start with your own new[] in the first place (ugh) though you can at least wrap all this in some class that mimics std::vector and becomes non-owning.

这篇关于销毁std :: vector而不释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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