【发布时间】:2014-12-18 15:27:29
【问题描述】:
似乎std::unique_ptr 解决了一个也可以通过移动语义解决的问题,即转移唯一拥有资源的所有权。以下是他们似乎执行相同工作的一些示例:
class SomeResource { /* resourcey stuff */ };
void ProcessResourcePtr(std::unique_ptr<SomeResource> r) { /* do stuff */ }
void ProcessResourceRvalRef(SomeResource&& r) { /* do stuff */ }
class OwnerOfResourcePtr {
private:
std::unique_ptr<SomeResource> r_;
public:
OwnerOfResourcePtr(std::unique_ptr<SomeResource> r) : r_(std::move(r)) { }
};
class OwnerOfResourceRvalRef {
private:
SomeResource r_;
public:
OwnerOfResourceRvalRef(SomeResource&& r) : r_(std::move(r)) { }
};
int main()
{
// transfer ownership to function via unique_ptr
std::unique_ptr<SomeResource> r1(new SomeResource());
ProcessResourcePtr(std::move(r1));
// transfer ownership to function via rvalue ref
SomeResource r2;
ProcessResourceRvalRef(std::move(r2));
// transfer ownership to instance via unique_ptr
std::unique_ptr<SomeResource> r3(new SomeResource());
OwnerOfResourcePtr(std::move(r3));
// transfer ownership to instance via rvalue ref
SomeResource r4;
OwnerOfResourceRvalRef(std::move(r4));
return 0;
}
在我看来,它们都以略微不同的方式解决了几乎完全相同的问题。我不是 100% 清楚一种方式与另一种方式的优势。我知道指针移动可能比移动构造函数/赋值更快,尽管通常认为两者都非常有效。我也知道移动语义允许您将数据保留在堆栈上(请参阅 r2、r4),而不是需要使用 new/malloc/etc 进行堆分配/释放(请参阅 r1、r3),我认为这是一个很好的选择东西(是吗?)。
一般来说,什么时候应该更喜欢 unique_ptr 而不是移动语义,反之亦然?是否有任何用例只能通过一个或另一个来解决?
【问题讨论】:
标签: c++ c++11 move-semantics unique-ptr