I would vote against defining a single setter for passing arguments by value:
- When a value needs to be copied, it will always have to allocate new memory. Taking an argument in by reference and assigning it to the internal variable could reuse existing capacity.
void set(const std::vector<int>& v)
{
// this->v may already be allocated, reuse it
this->v = v;
}
- Setters taking in an rvalue reference can often be declated
noexcept
. Although technically exceptions thrown while passing an argument don't violate the noexcept guarantee, it may be counter-intuitive for users.
void set(std::vector<int>&& v) noexcept
{
static_assert(std::is_nothrow_move_assignable_v<decltype(v)>);
this->v = std::move(v);
}
/*
// Technically also works but calling a noexcept function which potentially
// may throw an exception while making a copy of an argument can be confusing
void set(std::vector<int> v) noexcept
{
this->v = std::move(v);
} */
When a setter has only one parameter I would recommend two setters taking lvalue and rvalue references. Setters are typically simple methods, so there will be (almost) no code duplication. In case of a complex setter, you may internally define a template method (or a free function) taking in a universal reference:
void MyClass::set(const std::vector<int>& v)
{
setHelper(v);
}
void MyClass::set(std::vector<int>&& v)
{
setHelper(std::move(v));
}
template<typename T>
void MyClass::setHelper(T&& v)
{
// Some complex code ...
this->v = std::forward<T>(v);
// More complex code ...
}