[英]std::move on object pointed to by a unique_ptr
移動unique_ptr
指向的對象而不是uptr本身是否合法? 例如std::unique_ptr<Foo> uptr(new Foo()); Foo bar = std::move(*uptr);
std::unique_ptr<Foo> uptr(new Foo()); Foo bar = std::move(*uptr);
有潛在的陷阱嗎?
std::move
語義表明在移動時,對象處於有效但未指定的狀態。 reset
/ release
unique_ptr
仍然安全嗎?
我嘗試將其用於矢量並有效-https://ideone.com/d1OfUm
int main() {
std::unique_ptr<std::vector<int> > uptr(new std::vector<int>);
uptr->push_back(23);
uptr->push_back(45);
uptr->push_back(34);
std::cout << "uptr size = " << uptr->size() << std::endl;
for (auto i=0; i < uptr->size(); ++i) {
std::cout << "(*uptr)[" << i << "] = " << (*uptr)[i] << std::endl;
}
std::cout << std::endl;
std::vector<int> v = std::move(*uptr);
std::cout << "uptr size post move = " << uptr->size() << std::endl;
for (auto i=0; i < uptr->size(); ++i) {
std::cout << "(*uptr)[" << i << "] = " << (*uptr)[i] << std::endl;
}
std::cout << std::endl;
std::cout << "moved vec size = " << v.size() << std::endl;
for (auto i=0; i < v.size(); ++i) {
std::cout << "v[" << i << "] = " << v[i] << std::endl;
}
std::cout << std::endl;
return 0;
}
std :: move語義表明在移動時,對象處於有效但未指定的狀態。
對於標准庫類而言,這是正確的。 對於定義明確的用戶定義類也應為true。 但是您確實可以創建自己的類,並按照自己的規則播放。 如果可以的話,請盡量避免它。
唯一_重置重置/發布仍然安全嗎?
如果該對象處於有效狀態,則無論通過unique_ptr還是以其他方式銷毀它,都是安全的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.