的move
是冗余的。
我自己,我应该这样做:
void takeOwnership(std::unique_ptr<MyObject> nowItsReallyMyObject)
{
myObjects.emplace_back(std::move(nowItsReallyMyObject));
}
因为我想移动unique_ptr
所有权语义据“走出去”成为可能。
我可能会这样写效用函数:
template<class T>
std::unique_ptr<T> wrap_in_unique(T* t) {
return std::unique_ptr<T>(t);
}
所以呼叫者可以:
foo.takeOwnership(wrap_in_unique(some_ptr));
但更重要的,则可以推unique_ptr
语义走出国界,只要它们能合理。
我可能连做:
template<class T>
std::unique_ptr<T> wrap_in_unique(T*&& t) {
auto* tmp = t;
t = 0;
return std::unique_ptr<T>(tmp);
}
template<class T>
std::unique_ptr<T> wrap_in_unique(std::unique_ptr<T> t) {
return std::move(t);
}
,它可以让来电者转变他们的T*
到unique_ptr
更容易。它们的所有T*
- >unique_ptr<T>
现在包装在一个std::move
中,并将源指针设置为零。
所以,如果他们有
struct I_am_legacy {
T* I_own_this = 0;
void GiveMyStuffTo(SomeClass& sc) {
sc.takeOwnership(wrap_in_unique(std::move(I_own_this)));
}
};
的代码可被转换成:
struct I_am_legacy {
std::unique_ptr<T> I_own_this;
void GiveMyStuffTo(SomeClass& sc) {
sc.takeOwnership(wrap_in_unique(std::move(I_own_this)));
}
};
,它仍然编译和工作原理相同。 (与I_own_this
的其他交互可能需要更改,但其中的一部分已经与unique_ptr兼容)。
你不需要'std :: move'。 – juanchopanza
在基元类型(指针)上调用'std :: move'没有意义。 –