众所周知,C++里面有移动构造函数和拷贝构造函数,一般来说拷贝构造函数比移动构造函数效率更低。考虑一个场景:vector里面的元素是类的对像,并且该类的对象提供移动构造函数,那么当vector扩容时,需要把元素从老的内存空间移动到新的内存空间,那么此时STL会调用移动构造函数吗?看如下例子(test.cpp):
#include <iostream>
using namespace std;
class Test
{
public:
Test(){printf("constructor!\r\n");};
Test(const Test& test) { printf("copy constructor!\r\n"); }
Test(const Test&& test) { printf("move constructor!\r\n"); }
};
int main()
{
vector<Test> testList;
int n = 10;
for(int i = 0; i < n; i++)
{
printf("i = %d, cap = %d\r\n", i, testList.capacity());
testList.push_back(Test());
}
return 0;
}
编译:g++ test.cpp -o test
运行:./test
结果如下:
很奇怪,程序并没有如期望的那样调用移动构造函数,而是调用拷贝构造函数。这是为什么呢,原来STL在选择调用移动构造函数还是拷贝构造函数时,首先要考虑的是,已经存在的元素能否安全地从老的内存空间转移到新的内存空间,一般来说拷贝会比移动更加安全一点,所以在同等情况下会优先考虑用拷贝构造函数。但是,如果移动构造函数加了关键字noexcept申明了移动构造函数不会抛出异常,也就是说移动构造函数是安全的,那么STL将会选择移动构造函数而不是拷贝构造函数。更新过的代码如下:
#include <vector>
#include <iostream>
using namespace std;
class Test
{
public:
Test(){printf("constructor!\r\n");};
Test(const Test& test) { printf("copy constructor!\r\n"); }
Test(const Test&& test) noexcept { printf("move constructor!\r\n"); }
//增加关键字"noexcept"申明
};
int main()
{
vector<Test> testList;
int n = 10;
for(int i = 0; i < n; i++)
{
printf("i = %d, cap = %d\r\n", i, testList.capacity());
testList.push_back(Test());
}
return 0;
}
编译并运行如下: