为什么调用从对象移动的析构函数? [英] Why destructor of a moved from object is invoked?
问题描述
请考虑下面的代码:
struct foo {
std :: string id;
};
int main(){
std :: vector< foo> v;
{
foo tmp;
v.push_back(std :: move(tmp));
}
}
在代码段中展示:
-
foo
的默认构造函数将被调用来构造对象tmp
。 -
foo
将在语句v.push_back(std :: move(tmp));
中调用。 -
class foo
的析构函数将被调用两次。
问题:
- 为什么从对象移动的析构函数被调用两次? li>
- 从正在移动的对象移动的是什么?
为什么被移动对象的析构函数被调用两次?当
main()中的第一个
。第二个析构函数破坏了移动构造的}
超出范围时,从 tmp
foo
,将 push_back
'转换为当
v
超出范围时, main()
b
$ b
从正在移动的对象中移动什么?
编译器生成的移动构造函数move-constructs id
,它是一个 std :: string
。 std :: string
的移动构造函数通常获取存储实际字符串的移动对象中的内存块的所有权,并将移动的对象设置为有效但未指定状态(实际上,可能是一个空字符串)。
Consider the following piece of code:
struct foo {
std::string id;
};
int main() {
std::vector<foo> v;
{
foo tmp;
v.push_back(std::move(tmp));
}
}
In the piece of code demonstrated:
- The default constructor of class
foo
is going to be invoked for the construction of objecttmp
. - The move constructor of class
foo
is going to be invoked in the statementv.push_back(std::move(tmp));
. - The destructor of
class foo
is going to be invoked twice.
Questions:
- Why the destructor of a moved from object is called twice?
- What is moved from the object that is being moved really?
Why the destructor of a moved object is called twice?
The first destructor destroys the moved-from tmp
when it goes out of scope at the first }
in main()
. The second destructor destroys the move-constructed foo
that you push_back
'd into v
at the end of main()
when v
goes out of scope.
What is moved from the object that is being moved really?
The compiler-generated move constructor move-constructs id
, which is a std::string
. A move constructor of std::string
typically takes ownership of the block of memory in the moved-from object storing the actual string, and sets the moved-from object to a valid but unspecified state (in practice, likely an empty string).
这篇关于为什么调用从对象移动的析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!