vendredi 23 octobre 2020

Best way to create a setter function in C++

I want to write a template function that receives parameter by move or by copy. The most efficient way that I use is:

void setA(A a)
{
   m_a = std::move(a);
}

Here, when we use is

A a;
setA(a);            // <<---- one copy ctor & one move ctor
setA(std::move(a)); // <<---- two move ctors

I recently found out that defining it this way, with two functions:

void setA(A&& a)
{
   m_a = std::move(a);
}
void setA(const A& a)
{
   m_a = a;  // of course we can so "m_a = std::move(a);" too, since it will do nothing
}

Will save a lot!

A a;
setA(a);            // <<---- one copy ctor
setA(std::move(a)); // <<---- one move ctor

This is great! for one parameter... what is the best way to create a function with 10 parameters?!

void setAAndBAndCAndDAndEAndF...()

Any one has any ideas? Thanks!

Aucun commentaire:

Enregistrer un commentaire