我可以强制 std::vector 留下内存泄漏吗?

编程入门 行业动态 更新时间:2024-10-15 02:24:29
本文介绍了我可以强制 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 留下内存泄漏吗?

本文发布于:2023-10-31 13:49:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1546270.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存   std   vector

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!