我想知道为什么std :: vector在动态增长时不使用move构造函数。或者我的代码有问题吗?请参阅下面的测试代码:
#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();
}
上述代码的输出如下:
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
即使类test
具有移动构造函数,仍然向量使用复制
构造函数在内部调整大小时。这是预期的行为还是它
因为test
类本身存在一些问题?
感谢您的回答。