0

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?

AspiringMat
  • 2,161
  • 2
  • 21
  • 33

1 Answers1

1

Why isn't the move constructor called?

Because there is no scope of it getting called. If you expect it to be called in auto && v = build(100000);, then it's not correct, because v is an r-value reference variable and not an object. Constructors get called upon objects.

Any idea why the copy constructor is not called when returned by the function?

That's because of copy elision and return value optimisation. You may get more info here: What are copy elision and return value optimization?

iammilind
  • 68,093
  • 33
  • 169
  • 336