我可以强制 std::vector 留下内存泄漏吗? [英] Can I force std::vector to leave a memory leak?

查看:26
本文介绍了我可以强制 std::vector 留下内存泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在向量超出范围后,我可以强制 std::vector 不释放其内存吗?

Can I force std::vector to not deallocate its memory after the vector goes out of scope?

例如,如果我有

int* foo() {
    std::vector<int> v(10,1); // trivial vector
    return &v[0];
}

int main()
{
    int* bar = foo();
    std::cout << bar[5] << std::endl;
}

无法保证此处仍可访问这些值.

There is no guarantee that the values will still be accessible here.

我目前只是这样做

int* foo() {
  std::vector<int> v(10,1);
  int* w = new int[10];
  for (int i=0; i<10; i++) {
    w[i] = v[i];
  }
  return w;
}

但是重新填充一个全新的数组有点浪费.有没有办法强制 std::vector 不删除它的数组?

but it is a little wasteful to repopulate a whole new array. Is there a way to force std::vector to not delete its array?

注意:我没有返回向量本身,因为我使用 SWIG 将 c++ 与 python 连接起来,并且 ARG_OUTVIEW_ARRAY 需要一个原始指针,实际上,这是一个有意的内存泄漏.然而,我仍然希望能够在构建数据本身的同时利用矢量特征.

Note: I am not returning the vector itself because I am interfacing c++ with python using SWIG, and ARG_OUTVIEW_ARRAY requires a raw pointer and, in fact, an intentional memory leak. I would still however like to be able to make use of vector features while constructing the data itself.

推荐答案

vector 旨在防止泄漏.

但如果你想用脚射击自己,这是可能的.以下是防止向量释放其内部数组的方法:

But if you want to shoot yourself in the foot, it's possible. Here's how you prevent the vector from deallocating its internal array:

int *foo()
{
    std::vector<int> v(10,1);

    int *ret = v.data();
    new (&v) std::vector<int>; // Replace `v` with an empty vector. Old storage is leaked.
    return ret;
}

正如其他答案所说,你永远不应该这样做.

As the other answers say, you should never do it.

这篇关于我可以强制 std::vector 留下内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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