【发布时间】:2019-05-14 10:08:52
【问题描述】:
我可以强制 std::vector 在向量超出范围后不释放其内存吗?
例如,如果我有
int* foo() {
std::vector<int> v(10,1); // trivial vector
return &v[0];
}
int main()
{
int* bar = foo();
std::cout << bar[5] << std::endl;
}
无法保证这些值仍可在此处访问。
我目前只是这样做
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 不删除它的数组?
注意:我没有返回向量本身,因为我正在使用 SWIG 将 c++ 与 python 连接,而ARG_OUTVIEW_ARRAY 需要一个原始指针,实际上是故意的内存泄漏。然而,我仍然希望能够在构建数据本身时利用矢量特征。
【问题讨论】:
-
为什么
foo不返回int?最终有人必须存储价值...... -
@TheZhengmeister:为什么不把
std::vector<int> v = new std::vector<int>(10,1);换成foo? -
为什么不在 SWIG 中使用原始数组?这是可能的。
-
@TheZhengmeister 不,这是个糟糕的主意。如果你返回
&(*v)[0],即使你释放了它的内部数组,你也会泄漏向量本身。 -
%include <std_vector.i>then%template(IntVector) std::vector<int>;将允许传递和返回向量。