2
移动由unique_ptr
指向的对象而不是uptr本身是合法的吗?例如std::unique_ptr<Foo> uptr(new Foo()); Foo bar = std::move(*uptr);
任何潜在的问题?std ::在由unique_ptr指向的对象上移动
std::move
语义状态,在移动时,对象处于有效但未指定的状态。 unique_ptr
reset
/release
仍然安全吗?
我想这对向量和它的作品 - 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;
}
为什么你需要这样做?为什么不移动指针本身?这将是安全的,可以理解的和简单的 –
如果您从指向的对象移动,那么unique_ptr完全不涉及。只要对象本身能够正确处理移动,就不会有问题。 –
@AndrewLavq例如,假设您有一个对象,您可以从工厂函数中以'unique_ptr'的形式获得对象,然后需要将其放入具有合理值语义的集合中。 –