C++ Logo

std-discussion

Advanced search

Re: Move from const object

From: Bo Persson <bo_at_[hidden]>
Date: Mon, 27 Jun 2022 23:45:24 +0200
On 2022-06-27 at 21:14, Martin Küttler via Std-Discussion wrote:
>
> 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.
>

Possibly by not painting themselves into this corner. :-)

Why is the Foo move-only? And why is it then also const, but assumed to
still move around?

The most common move-only standard types are the stream classes. But
what is the use of a const stream? So this problem doesn't occur there.

Received on 2022-06-27 21:45:53