How to return not copied, movable object by value as const and save it?

class A; const A getA(); 

A - fixed, mobile. getA () - creates and returns A, as const.

How to do it?

 const A a = getA(); 

I can only do this.

 const A& a = getA(); 
+6
source share
1 answer

Do not return the value as const . When you return something, you say: "The caller is here, now it's yours. Do what you want with him." If the calling object of your method does not want to change it, it can save it as const , as you showed above: const A a = getA(); . But you (as a method) should not tell the caller whether its objects are const or not (your return value is its object).

If your return value is const , you cannot move from it to your new object, so your move constructor is not even considered. The only option is copying, which does not work, because in your case it is not a copyable object. If the return is not const, you can jump from it and you will get the desired behavior.

+10
source

Source: https://habr.com/ru/post/947109/


All Articles