[英]std::vector::insert() stopped working when migrating from MSVC 2013 (C++11) to MSVC 2019 (C++17)
I currently am migrating a large code base from我目前正在从
to到
and now, my tests fail in strange places - I get index out of bounds crashes and other strange changes in behavior.现在,我的测试在奇怪的地方失败了 - 我的索引越界崩溃和其他奇怪的行为变化。 Upon digging I noticed that the following code:
在挖掘时,我注意到以下代码:
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<int>> nestedVector;
nestedVector.insert(nestedVector.begin(), {});
std::cout << nestedVector.size() << " elements";
}
produces a one-element vector in VS2013 but an empty vector in VS2019.在 VS2013 中产生一个单元素向量,但在 VS2019 中产生一个空向量。
Other ways of inserting其他插入方式
nestedVector.insert(nestedVector.begin(), std::vector<int>{});
nestedVector.insert(nestedVector.begin(), std::vector<int>());
work in both setups and properly add a new element.在两种设置中工作并正确添加新元素。 What is happening here?
这里发生了什么?
As was already mentioned in the comments, in your original program the call of nestedVector.insert(nestedVector.begin(), {})
selects the overloaded method:正如评论中已经提到的,在您的原始程序中,调用
nestedVector.insert(nestedVector.begin(), {})
选择了重载方法:
iterator insert( const_iterator pos, std::initializer_list<T> ilist );
see https://en.cppreference.com/w/cpp/container/vector/insert .请参阅https://en.cppreference.com/w/cpp/container/vector/insert 。
Since the initializer list is empty, nothing is really inserted and the vector size is zero at the end.由于初始值设定项列表是空的,因此没有真正插入任何内容,并且最后向量大小为零。 It is the same behavior in all compilers, demo: https://godbolt.org/z/9nnET5ren
在所有编译器中都是相同的行为,演示: https : //godbolt.org/z/9nnET5ren
Apparently, VS2013 did not implement this overload of insert
method, so another one called:显然,VS2013没有实现这个
insert
方法的重载,所以另一个调用:
iterator insert( const_iterator pos, const T& value );
creating one element in the vector.在向量中创建一个元素。 This is wrong behavior.
这是错误的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.