C++ 移动构造函数在vector扩容时的场景

众所周知,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;
}
                                                                         

编译并运行如下:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一条叫做nemo的鱼

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值