问题描述
我有一块这样的代码:
class Data
{
public:
Data(const std::vector<int> &_data)
{
my_data = _data;
}
private:
std::vector<int> my_data;
};
int main()
{
std::vector<std::shared_ptr<Data>> vec = {
std::shared_ptr<Data>(new Data(std::vector<int>({ 1, 2 ,3 }))),
std::shared_ptr<Data>(new Data(std::vector<int>({ 3, 4 ,5 })))
};
// breakpoint
return 0;
}
不知何故,当我暂停程序检查值(在断点处) ( vec [0]
)元素被销毁,而第二个( vec [1]
这里发生了什么?这是编译器中的错误吗?我使用新的Visual Studio 2013。
somehow when I pause the program to check values (at breakpoint), the first (vec[0]
) element is destroyed while the second one (vec[1]
) is fine. What is going on here? Is that a bug in compiler? I am using new Visual Studio 2013.
推荐答案
会发生什么是VS2013中的错误导致双删除第一项initializer_list。
以下是流程:
What happens is that a bug in VS2013 causes a double delete on the first item of the initializer_list.Here's the flow:
- 构建了initializer_list。
- 目标向量保留(通过复制构造函数)复制1和第一个项目。
- 向量慢慢地变为initializer_list大小。
- initializer_list通过向量 - 析构函数(即
delete []
)。最后元素首先被销毁。 - 第一个元素通过scalar-destructor被再次销毁(即
delete
)。
- initializer_list is constructed.
- target vector is reserved a size of 1 and first item is copied (via copy constructor).
- vector grows slowly to initializer_list size.
- initializer_list is destroyed via a vector-destructor (i.e.
delete[]
). Last element is destroyed first. - First element is destroyed again via scalar-destructor (i.e.
delete
).
我在另一篇文章中看到这个,并使用调试器验证了这个行为。
请参见
I've seen this on another post and verified the behavior using a debugger.See here
对于VS2013,initializer_list仅适用于基本类型。
For VS2013, initializer_list is good for basic types only.
这篇关于为什么第一个元素被销毁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!