0

My code is this:

#include <vector>
#include <iostream>


class A{

        public:

        A() = default;

        A(const A& obj){
                std::cout << "Copy c-tor" << std::endl;
        }

        A(A&& obj){
                std::cout << "Move c-tor" << std::endl;
        }
};



int main(int argc, char *argv[]){

        std::vector<A> vA;

        std::cout << "Copy ctor will be invoked: " << std::endl;
        auto a = A();
        vA.push_back(a);

        std::cout << "Move ctor will be invoked: " << std::endl;
        vA.push_back(A());

        return 0;
}

I expected that there is one copy constructor invocation and one move constructor invocation. But the output has one two copy constructor call. As it is:

[amirreza@localhost copy]$ g++ copy.cpp 
[amirreza@localhost copy]$ ./a.out 
Copy ctor will be invoked: 
Copy c-tor
Move ctor will be invoked: 
Move c-tor
Copy c-tor

Why the copy ctor is called last time? Why the copy constructor is called twice?

Amir reza Riahi
  • 1,540
  • 2
  • 8
  • 34
  • 4
    You should `reserve` space in the vector before putting stuff in it, otherwise your output may get confusing due to resizing of the vector. – David Schwartz Aug 04 '22 at 20:07
  • 1
    I've linked to dupes explaining why you see the "extra" copy and also how to turn that copy into a move operation instead. – NathanOliver Aug 04 '22 at 20:07

0 Answers0