Alex Rivera | Logout

Why when one member cannot be moved, the whole enclosing class cannot be moved?

Asked 2011-11-29T22:18:22.877
11

Example

struct MyObject {
  MyObject(int value):value(value) { }
  MyObject(MyObject const&o):value(o.value) { }

  int value;
};

Assume that the copy constructor does something in addition to be useful. Then

std::function<void()> f() {
  MyObject o;
  std::vector<int> v;
  return [=]() { /* use v and o */ &o; &v; }
}

v and o are first copied into the initial lambda object, which is fine. But then they are again copied everytime the lambda object needs to be moved. Even though v could be moved, but it is not. That's because the lambda does not have an implicit move constructor, because o does not have a move constructor or trivial copy constructor.

Can someone please explain the rationale behind this?

Edit
Report

1 Answer

1

Kinda guessing, but I suspect it may have to do with exceptions. That is, move constructors should really be noexcept, but having a move constructor call a copy constructor could have it throw.

(trying to refresh my memory from here, which I think covered this issue)

EDITED TO ADD:

And my guess was wrong. The correct answer, as far as I can tell, is from here. The presence of the copy constructor is an indication that the class has invariants, and the default generated move constructor might not respect those invariants, and therefor, should not be generated.

answered 2011-11-29T22:59:36.657

Your Answer