0

I'm practicing with std::move wih std::vector::push_back. I have this simple code:

struct A
{
    A(int i,bool b,float f) : _i(i), _b(b), _f(f) {}
    A(const A& a)
    {
        std::cout << "copy constructor" << std::endl;
    }
    A(A&& a)
    {
        std::cout << "move constructor" << std::endl;
    }
    int _i;
    bool _b; 
    float _f; 
};

struct B
{
    template <typename T>
    void Add(T&& t) // universal reference
    {
        _v.push_back(std::move(t));
    }

private: 
    std::vector<A> _v; 
};


int main() {

    A a(1, false, 2.f);
    B b; 
    std::cout << "using rValue" << std::endl;
    b.Add(A(1, true, 2.f));
    std::cout << "using lValue" << std::endl;
    b.Add(a);
    return 0;
}

the output for some reason is :

using rValue
move constructor
using lValue
move constructor
copy constructor

Why is the copy constructor still invoked? shouldn't I have only move-constructors in my output??

Evethir
  • 31
  • 3
  • 1
    The setup was slightly different in that question, but the core issue is the vector reallocation before second `push_back` occurs. – Yksisarvinen Jul 21 '20 at 15:36
  • 2
    If you mark the move constructor `noexcept`, you should see two moves instead of one move and one copy, as the vector would be able to move (rather than copy) elements into new block of storage when reallocating. – Igor Tandetnik Jul 21 '20 at 15:38
  • Ehi Guys, thanks for the comments, the copy constructor was called because when adding the new object (which was made with move as expected), the vector had to resize itself, then a new memory area was allocated in which the first object was copied, which caused the invocation of the copy constructor :) – Evethir Jul 22 '20 at 08:08

0 Answers0