I want to reduce copying to a minimum, especially for expensive types/classes. So I could define overloads like this:
void SetParams(const std::map<int, std::string> ¶ms) { mParams = parameters; }
void SetParams(std::map<int, std::string> &¶ms) { mParams = std::move(params); }
void SetBoardInfo(const DataInfoStruct &board_info) { mBoardInfo = board_info; }
void SetBoardInfo(DataInfoStruct &&board_info) { mBoardInfo = std::move(board_info); }
in a class that has a std::map member variable called mParams and a DataInfoStruct struct member called mBoardInfo.
Since DataInfoStruct has no user defined constructors or destructors I assume that it has an implicit move constructor.
Then I can invoke either one of the overloads with an lvalue or rvalue. However, I could just have one version of each function like so:
void SetParams(std::map<int, std::string> params) { mParams = std::move(params); }
void SetBoardInfo(DataInfoStruct board_info) { mBoardInfo = std::move(board_info); }
In the second way I will always create a copy because I am passing by value, but then I move the parameter into the member variable. If I pass an rvalue I do no copying at all, but for an lvalue there will be one copy made always - which I will do any way if I used the first method.
Which of the two methods is recommended? Are rvalue references best used only for constructors and assignment operators?
Aucun commentaire:
Enregistrer un commentaire