is it overkill to use stdmove?

Reading the core guidelines at F.call: Parameter passing, we can deduce a few recommendations.

Use move only when you want to optimize for rvalue. If you find that it does an improvement on performance, it’s up to you to do it.

You could receive by value then move as it optimises rvalues calls into your setters, but it pessimizes lvalues. This is because std::string will reuse its storage and not cause unnecessary allocations when copying from the const reference. Copying into the value parameter always end up allocating when no SSO is possible.

The preferred way, especially for setters are to use const reference, and add an rvalue reference overload when rvalues are passed into the setter:

class Student
{
    private: 
        std::string _studentName;
        int _studentGrade;
    public:
        Student() : _studentName("No Name"), _studentGrade(0) {}

        std::string_view Name() const { return _studentName; }
        void Name(std::string const& x) { _studentName = x; }

        // add this when you need to optimize for rvalues.
        // optimizing for rvalues is not always needed.
        // They can speedup quite a bit when actually needed.
        void Name(std::string&& x) { _studentName = std::move(x); }

        // int is a trivial type, so move does nothing. No move needed.
        int Grade() const { return _studentGrade; }
        void Grade(int x) { _studentGrade = x; }
}

For the int, std::move won’t do anything, it’s still a copy. Just take them by value and return them by value.

However, the best you can do is much simpler:

class Student
{
public:
    std::string studentName;
    int studentGrade;
};

Since your setters don’t enforce any invariants, you’d be better off using public members. You don’t need overloads and reference since std::string implements it for you.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top