Friday, October 4, 2019

c++ - When should I supply a move-aware overload?




If I have a class that manages some dynamic memory (e.g. a vector-type class) and it already has a move-constructor, does it ever make sense to supply a move-aware overload for a function, or will the move-constructor take care of it?



For instance, which of these (if any) should I overload with a Class&& variant:




// the move-aware overload for all of these would be
// void FuncX(Class&&);

void Func1(Class);

void Func3(Class&); // doesn't make a local copy
void Func4(Class&); // makes a local copy

void Func5(Class const);


void Func7(Class const&); // doesn't make a local copy
void Func8(Class const&); // makes a local copy


Do any of them lose optimization opportunities because I am not supplying a move-aware variant?


Answer



Func1 and Func5 have the same signature, and are already "move-aware" because they can be called with lvalues or rvalues and the argument can be move constructed when passed an rvalue.



Func3 and Func4 cannot be called with rvalues at the moment, overloading them with Func(Class&&) would be a major change in semantics, not just an optimisation.




Func7 can already be called with rvalues and there is nothing to initialize via copy or move, overloading it would be pointless.



Func8 can be called with rvalues but performs a copy, changing that function to Func8(Class) would initialize the argument using either a copy or a move, depending on whether it was called with an lvalue or rvalue. Alternatively, overloading it with Func8(Class&&) would also allow you to avoid the copy when passing an rvalue, but now you have two functions to maintain.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...