C++ Logo

std-discussion

Advanced search

Move from const object

From: Martin Küttler <martin.kuettler_at_[hidden]>
Date: Mon, 27 Jun 2022 21:14:52 +0200
Hi,

I recently understood that

struct Foo {
  Foo(Foo const &) = delete;
  Foo(Foo &&) = default;
};

Foo f() {
  Foo const foo{};
  return foo;
}

main() {
  auto foo = f();
  return 0;
}

does not compile. That is because the const foo in f can not be moved
from. That makes a lot of sense in theory, but it is sometimes a problem
with using const in practice.

The (trivial) example compiles if the const in f is removed. I do not
fully understand the interaction with objects that are actually
bit-const in contrast to just being declared const.

In the given situation it would seem ideal to me if the compiler could
tell that the const is not needed anymore, and the Move-Ctor can be
called. Destructors are being called as well, after all, and typically
also need non-const objects.

I guess my question is not so much a proposal, but I wonder if this
situation is understood and considered ok, or if some fix is planned. To
me this seems to be a significant problem with const variables, so in
case no fix is planned, I wonder how a programmer is supposed to work
around this.

Best regards,
Martin Küttler

Received on 2022-06-27 19:14:55