简体   繁体   English

C ++ std :: vector segfault在使用delete()时使用,在pop_back()与g ++一起使用时可以

[英]C++ std::vector segfault when using erase(), ok when using pop_back() with g++

Please consider the following code: 请考虑以下代码:

vector<int> myVector;
myVector.push_back(10);
myVector.erase(myVector.end());

This code compiles and runs fine on Windows (VisualStudio), but results in a segfault on Linux when compiled with g++. 该代码可以在Windows(VisualStudio)上编译并正常运行,但是使用g ++进行编译时会在Linux上产生段错误。 Replacing erase with pop_back solves the problem on Linux. 用pop_back替换擦除可解决Linux上的问题。

Does anyone know why the behaviour is different on the two platforms, and what behaviour to consider correct. 有谁知道为什么这两种平台上的行为不同,以及什么行为可以纠正。

Thanks in advance! 提前致谢!

end() typically returns an invalid position in the array (one beyond the end). end()通常会在数组中返回无效位置(超出末尾的位置)。

pop_back() removes the last item in the vector. pop_back()删除向量中的最后一项。

If you want to erase, you have to do erase(end() - 1); 如果要擦除,则必须erase(end() - 1); here end() - 1 returns an iterator to the last item. 在这里end() - 1将迭代器返回到最后一项。

erase(end()) should invoke UB - which I think is correct... erase(end())应该调用UB-我认为是正确的...

EDIT: as Martin pointed out, before calling erase(end() - 1) , check that the vector is not empty! 编辑:正如马丁指出的那样,在调用erase(end() - 1) ,请检查向量是否为空!

end()指向无处,那是无尽的。

myVector.end() does not point to the last element of the vector. myVector.end()不指向向量的最后一个元素。 It points past the last element of the vector. 它指出过去的向量的最后一个元素。 I am not sure, though, if this qualifies as undefined behavior (if it does, then it is reasonable that Windows and Linux behave differently). 但是,我不确定这是否属于未定义的行为(如果确实如此,则Windows和Linux行为不同是合理的)。

myVector.end() gives you an iterator to right after the last element in your vector. myVector.end()为您提供一个迭代器,使您可以在向量中的最后一个元素之后进行迭代。 As there isn't anything there, calling erase on it doesn't make much sense. 由于那里没有任何东西,因此对其进行呼叫擦除没有多大意义。

I am curious to find out exactly what Visual Studio is doing when you call that though. 我很好奇地想确切地知道当您调用Visual Studio时在做什么。 Run some tests to see if it is actually erasing the 10 from your vector, or if it is just gracefully ignoring your incorrect request. 运行一些测试,以查看它是否实际上已从引导程序中擦除10 ,或者只是从容地忽略了您的错误请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM