Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a non-copyable, movable object by-value as const and store it?

Tags:

c++

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();
like image 654
NFRCR Avatar asked Jun 12 '13 12:06

NFRCR


1 Answers

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.

like image 163
David Avatar answered Sep 27 '22 18:09

David