vendredi 24 décembre 2021

Should I move on return when variables are not local

A have a few questions regarding copy elision and move. Let's assume I have the following code:

class A {};

class B {
public:
    A get1() const {
        A local_var;
        return local_var;
    }
    A get1bad() const {
        A local_var;
        return std::move(local_var);
    }
    A get2() const {
        return member_var;
    }
    A get3() const {
        return std::move(member_var);
    }
private:
    A member_var;
};

I read a lot of people saying to not do move on return. From what I gather it's because with copy elision, on case get1, the compiler will not call constructor + move constructor but rather just one call to the default constructor, while case get1bad forces the compiler to call constructor + move.

My question is regarding cases where the variable is not local (get2 vs get3). In that case, the variable is constructed anyway in the class. In get2 there's not really any optimization that I can see being possible. In this case, if I don't really care about ensuring class B has a valid A object, wouldn't it be better to actually move? Wouldn't it just call the move constructor which is generally cheaper than the copy constructor?

Aucun commentaire:

Enregistrer un commentaire