lundi 9 mars 2020

Why isn't the move constructor called?

I just learned about move constructors, and was trying to write an example to test my understanding. I came up with this small wrapper around the std::vector class:

#include <iostream>
#include <utility>
#include <vector>

class Vector{
    std::vector<int> v;
public:
    Vector(int n):v(n, 1){std::cout << "In default constructor" << std::endl;};
    Vector(Vector&& _v){
        std::cout << "In Move constructor" << std::endl;
        v = std::move(_v.v);
    }

};
Vector build(int n){
    Vector v(n);
    return v;
}

int main() {
    auto && v = build(100000);
}

However, when I run this, the algorithm returns only: "In default constructor" referring to the original instantiation of the vector. Any idea why the copy constructor is not called when returned by the function? Any why the default constructor is not called again when instantiating the temporary rvalue returned by the function?

Aucun commentaire:

Enregistrer un commentaire