I want to write an class that optimizes a parameter. I thought the following interface would be desirable:
class Optimization {
public:
std::shared_ptr<Part> getParameter() const {
return m_parameter;
}
void setParameter(const std::shared_ptr<Parameter>& parameter) {
m_parameter = parameter;
}
private:
std::shared_ptr<Paramter> m_parameter;
};
Now sometimes I may not be interested in the starting value of the parameter so I would like to call setParameter like this:
setParameter(std::make_shared(Parameter(...)));
(now I guess it makes more sense why there is a getter function) So as I understand it the setParameter function is not taking advantage that I am passing an rvalue to setParameter.
So my question is how can I solve this?
Should I add another function
void setParameter(std::shared_ptr<Parameter>&& parameter) {
m_parameter = std::move(parameter);
}
Does this avoid unneccessary copies? Or would a universal reference, maybe like this:
template<typename T>
void setParameter(T&& parameter) {
m_parameter = std::forward<T>(parameter);
}
be a better solution?
The right implementation is like below
void setParameter(std::shared_ptr<Parameter> parameter) {
m_parameter = std::move(parameter);
}
parameter and parameter will be moved to m_parameter. Two moves, like you want.parameter and parameter will be moved to m_parameter. One copy and one move, the similar like with const reference, plus cheap moving that will be optimized.You can read about this in the book "Effective C++" of Scott Meyers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With