PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 5, 2022

[FIXED] What is the best practice when defining const& and && version of a set method?

 July 05, 2022     c++, c++20, move-semantics, pass-by-reference, setter     No comments   

Issue

If I want to define a method like a setter for a std::vector member (or movable object) I can do it like this:

 void set(const std::vector<int>& v) { _v = v; }

But also I need to add

 void set(std::vector<int>&& v) { _v = std::move(v); }

Right? Is it always best to define both in order to handle temporaries that can be move? So all setters will be doubled? Thanks.


Solution

If you know the type has an efficient move constructor (which std::vector<int> does), then you can just take by value and move from the argument:

void set(std::vector<int> v) { _v = std::move(v); }

That way, when called with an lvalue it will be copied, but when called with an rvalue it will be moved.



Answered By - Artyer
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing