Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setter function for shared_ptr

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?

like image 539
user3726947 Avatar asked Mar 11 '26 06:03

user3726947


1 Answers

The right implementation is like below

void setParameter(std::shared_ptr<Parameter> parameter) {
    m_parameter = std::move(parameter);
}
  1. rvalue will be moved to parameter and parameter will be moved to m_parameter. Two moves, like you want.
  2. lvalue will be copied to 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.

like image 103
273K Avatar answered Mar 13 '26 19:03

273K