When is overloading pass by reference (l-value and r-value) preferred to
pass-by-value?
I have seen it said that a operator= written to take a parameter of the
same type by-value serves as both copy assignment operator and move
assignment operator in C++11:
Foo& operator=(Foo f)
{
swap(f);
return *this;
}
Where the alternative would be more than twice as many lines with a lot of
code repetition, and potential for error:
Foo& operator=(const Foo& f)
{
Foo f2(f);
swap(f2);
return *this;
}
Foo& operator=(Foo&& f)
{
Foo f2(std::move(f));
swap(f2);
return *this;
}
In what circumstances is the ref-to-const and r-value overload preferable
to pass by value, or when is it necessary? I'm thinking about
std::vector::push_back, for example which is defined as two overloads:
void push_back (const value_type& val);
void push_back (value_type&& val);
Following the first example where pass by value serves as copy assignment
operator and move assignment operator, couldn't push_back be defined in
the Standard to be a single function?
void push_back (value_type val);
No comments:
Post a Comment