C ++ only moves objects - what to return from assignment operator
Given this canonical form of the move assignment operator:
class_name & class_name :: operator= ( class_name && )
When copying is disabled, binding is not possible, because the return value is lvalue
, and from a logical point of view, it doesn't make sense. The only place I can see (perhaps you have other samples) a return value that can be used is a function call that takes reference/const reference
to class_name
:
void foo(class_name&){}
void bar(const class_name&){}
void use_foo_bar()
{
some_class a;
foo(a = get_some_class());
bar(a = get_some_class());
}
but I see it as bad programming style (personal opinion) and I would hate to see it in the codebase.
Does it make sense to return the current object when the copy is out of void
order , or is the return type ok?
source to share
You can argue that chaining is never good and always returns the return type operator=
a void
.
But if you don't, you get rid of the mental overhead: "Is this a type of movement?" when writing a signature operator=
and do it the same for all types.
Edit: In other words, it is no longer necessary for you to write a statement in the usual way, than it is for readers of your code to figure out why you didn't.
source to share
Does it make sense to return the current object when the copy is disabled or the
void
Return type is OK?
There is general discussion on whether to operator=
return an assigned object or just void
. Many people say that the chaining capability leads to less readable code and encourages you to write multiple things on a single statement / line.
I assume your question is less philosophical, but more focused. In this case, consider that some chains are still working:
auto&& c = a = b;
c
is a reference (with a type class_name&
), not an object, so the returned lvalue reference from will operator=
initialize accordingly c
. This obviously also applies to function parameters, which are references, and there are quite a few of them:
template <typename T>
void f(T&& t);
// [โฆ]
f(a = b);
source to share