class A;
const A getA();
A - non-copyable, movable.
getA()
- constructs and returns an A
, as const
.
How to do this?
const A a = getA();
I can only do this.
const A& a = getA();
Don't return by value as const
. When you return anything you are saying "Here caller, this is yours now. Do what you want with it". If the caller of your method doesn't want to modify it, they can store it as const
, as you have shown above with: const A a = getA();
. But you (as a method) shouldn't be telling the caller whether their objects are const
or not (your return value is their object).
If your return value is const
you can't move
from it into your new object, so your move constructor is not even considered. The only option is copying, which doesn't work either because in your case it's a noncopyable object. If the return is non-const you can move from it, and you get the behavior you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With