什么是std :: move和unique_ptr :: reset之间的区别? [英] what are the differences between std::move and unique_ptr::reset?
问题描述
std :: unique_ptr
s p1
和 p2
, std :: move()
和 std :: unique_ptr :: reset()
? / p>
For std::unique_ptr
s p1
and p2
, what are differences between std::move()
and std::unique_ptr::reset()
?
p1 = std::move(p2);
p1.reset(p2.release());
推荐答案
分配给[unique.ptr.single.assign] / 2:
The answer should be obvious from the standard's specification of move assignment in [unique.ptr.single.assign]/2:
效果:如果通过调用
reset(u.release())$ c>,则
u $ c>后面是std :: forward< D>(u.get_deleter())
的分配。
Effects: Transfers ownership from
u
to*this
as if by callingreset(u.release())
followed by an assignment fromstd::forward<D>(u.get_deleter())
.
清除移动赋值不等于 reset(u.release())
,因为它有额外的功能。
Clearly move assignment is not the same as reset(u.release())
because it does something additional.
额外的效果很重要,没有它你可以得到未定义的行为与自定义删除:
The additional effect is important, without it you can get undefined behaviour with custom deleters:
#include <cstdlib>
#include <memory>
struct deleter
{
bool use_free;
template<typename T>
void operator()(T* p) const
{
if (use_free)
{
p->~T();
std::free(p);
}
else
delete p;
}
};
int main()
{
std::unique_ptr<int, deleter> p1((int*)std::malloc(sizeof(int)), deleter{true});
std::unique_ptr<int, deleter> p2;
std::unique_ptr<int, deleter> p3;
p2 = std::move(p1); // OK
p3.reset(p2.release()); // UNDEFINED BEHAVIOUR!
}
这篇关于什么是std :: move和unique_ptr :: reset之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!