I am wondering why the std::vector does not use move constructor when it grows dynamically. Or is it some problem with my code? Please see below my test code:
#include<vector>
#include<iostream>
#include<cstring>
using namespace std;
class test{
public:
char *ptr;
public:
test()
:ptr{new char[10]}{
strcpy(ptr,"hello");
cout<<"constructor called"<<endl;
}
test(const test& t){
ptr = new char[10];
strcpy(ptr,t.ptr);
cout<<"copy constructor called"<<endl;
}
test(test &&t){
this->ptr = t.ptr;
t.ptr = nullptr;
cout<<"move constructor called"<<endl;
}
~test(){
cout<<"destructor called"<<endl;
delete[] ptr;
}
};
vector<test> function()
{
vector<test> v;
cout<<v.size()<<" "<<v.capacity()<<endl;
v.push_back(test{});
cout<<v.size()<<" "<<v.capacity()<<endl;
v.push_back(test{});
cout<<v.size()<<" "<<v.capacity()<<endl;
return v;
}
int main()
{
vector<test> v = function();
}
the output of above code is as follows:
0 0
constructor called
move constructor called
destructor called
1 1
constructor called
move constructor called
copy constructor called
destructor called
destructor called
2 2
destructor called
destructor called
Even though the class test
has a move constructor, still vector uses copy
constructor when it resizes internally. Is it the expected behavior or is it
because of some problem with test
class itself?
thanks for your answers.