gpt4 book ai didi

c++ - 通过引用 c++ 删除对象

转载 作者:太空宇宙 更新时间:2023-11-04 14:44:07 31 4
gpt4 key购买 nike

我遇到了今天无法解释的问题。

int main(){
vector<int> vec = subroutine();
...
delete(&vec);
}

vector<int>& subroutine(){
vector<int>* vec = new vector<int>();
//Init the vec
for(int i=0;i<vec.size();i++){
...
}
return *vec;
}

它出现了一个错误:

double free or corruption (out): 0X00007fffa145ff50

肯定是线路的问题:

delete(&vec);

但是我就是解释不通,为什么会有double free?

最佳答案

您正在对未使用 new 分配的内容调用 delete,因为您正在制作新 vector 的拷贝。您可以通过不复制 vector 来“更正”您的代码:

vector<int>& vec = subroutine();

不过这种功能真的是自找麻烦。解决此问题的正确方法是按值返回 vector 。

vector<int> subroutine() {
vector<int> vec;
//Init the vec
for(int i=0;i<vec.size();i++){
...
}
return vec;
}

关于c++ - 通过引用 c++ 删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24492699/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com