lundi 15 août 2022

Move constructor for vec3 class

I'm trying to improve my cpp lately, and I want to write my own vec3 class to represent a 3D vector and point. I want it to hold 3 values of the same type and have some standard operations like addition and things...

I'm trying to learn more about move semantics and I'd like to create a move constructor that would take 3 literal ints like this: vec3<int> a(1, 2, 3); But this shows me error that more than one instance of constructor matches the argument list. Here is my code:

template <typename T>
class vec3 {
    T x, y, z;

    // standard copy ctor
    vec3(T _x, T _y, T _z): x(_x), y(_y), z(_z) {}
    // move ctor for rvalue references like vec3(1, 2, 3)
    vec3(T &&_x, T &&_y, T &&_z): x(_x), y(_y), z(_z) {}

    vec3<T> operator+(const vec3<T> &vec) {
        // I don't want to create 3 int's just to copy them
        return vec3<T>(this.x + vec.x,
                       this.y + vec.y,
                       this.z + vec.z);
    }
};

int main() {
    vec3<int> b(1, 2, 3); // more than one instance of constructor
                          // "vec3<T>::vec3 [with T=int]" matches the argument list:C/C++(309)

    int x, y, z = 5;
    vec3<int> c(x, y, z); // OK, it matches copy ctor
}

I'd like to know if my understanding of copy ctors is correct. Can I use it for moving simple, temporary int values into functions? Or is move semantics only for more complex types like std::vector? Is my way of thinking about moving temporary values directly into constructor correct?

I'd greatly appreciate help in this matter, and gladly read more about this topic. Any good articles with use cases would be helpful, as reading cpp reference doesn't help me a lot right now.

Aucun commentaire:

Enregistrer un commentaire