简体   繁体   English

为优化级别为 0 的 std::vector 调用两次析构函数

[英]destructor is called twice for std::vector with optimization level 0

I am trying to understand the assembly code generated for the std::vector and its emplace_back (or) push_back function using compiler explorer .我正在尝试使用compiler explorer理解为std::vector及其emplace_back (or) push_back函数生成的汇编代码。

Note: Optimization level is 0 ie, -O0 is used注意:优化级别为 0,即使用 -O0

One thing that I couldn't understand is that why are there two destructors being called instead of one (As you can see only one vector is being created. If I assume that a temporary object is being created internally, then atlease I have to see a call to std::vector constructor.我无法理解的一件事是,为什么要调用两个析构函数而不是一个析构函数(如您所见,只创建了一个向量。如果我假设在内部创建了一个临时对象,那么至少我必须看到对std::vector构造函数的调用。

This is same with clang compiler as well.这与 clang 编译器相同。

Can someone please explain what is happening here?有人可以解释一下这里发生了什么吗?

Edit 1:编辑1:

#include <vector>
int main()
{
    std::vector<int> vec;
    vec.emplace_back(10);
}

Edit 2: Removed the screenshot as it is hard to read it.编辑 2:删除了屏幕截图,因为它很难阅读。

There's a clue at line 34: call _Unwind_Resume .第 34 行有一条线索: call _Unwind_Resume That block of code, from lines 28 through 34, is for stack unwinding when an exception is thrown.该代码块,从第 28 行到第 34 行,用于在抛出异常时进行堆栈展开。 The normal code path goes through the destructor call at line 25, then, at line 27, jumps past the exception code, to line 35, and from there it returns from the function.正常的代码路径通过第 25 行的析构函数调用,然后在第 27 行跳过异常代码,跳转到第 35 行,然后从函数返回。

Just to clarify, there's magic here: the call to _Unwind_Resume does not return to the caller.澄清一下,这里有一个神奇之处:对_Unwind_Resume的调用不会返回给调用者。 It's a trick, to get the address of the block that was being executed, so that the exception handling code can figure out where it was and continue up the stack.这是一个技巧,获取正在执行的块的地址,以便异常处理代码可以确定它在哪里并继续向上堆栈。

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

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