a.n.g
a.n.g

Reputation: 31

std::move on object pointed to by a unique_ptr

Is it legal to move objects pointed to by a unique_ptr rather than the uptr itself? e.g. std::unique_ptr<Foo> uptr(new Foo()); Foo bar = std::move(*uptr); Any potential gotchas?

std::move semantics state that on moving, the object is in valid but unspecified state. Is the unique_ptr reset/release still safe?

I tried this for vectors and it works - 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;
}

Upvotes: 3

Views: 997

Answers (1)

user743382
user743382

Reputation:

std::move semantics state that on moving, the object is in valid but unspecified state.

That is true for standard library classes. It should also be true for well-defined user-defined classes. But you do have the ability to create your own classes that play by your own rules. Try to avoid it if you can though.

Is the unique_ptr reset/release still safe?

If the object is left in a valid state, then destroying it, whether through unique_ptr or otherwise, is safe.

Upvotes: 4

Related Questions