移动构造函数应用最多的地方就是STL中(原文详解移动构造函数)

移动构造函数应用最多的地方就是STL中

给出一个代码,大家自行验证使用move和不适用move的区别吧

移动构造函数应用最多的地方就是STL中(原文详解移动构造函数)
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <vector>
using namespace std;

class Str{
    public:
        char *str;
        Str(char value[])
        {
            cout<<"普通构造函数..."<<endl;
            str = NULL;
            int len = strlen(value);
            str = (char *)malloc(len + 1);
            memset(str,0,len + 1);
            strcpy(str,value);
        }
        Str(const Str &s)
        {
            cout<<"拷贝构造函数..."<<endl;
            str = NULL;
            int len = strlen(s.str);
            str = (char *)malloc(len + 1);
            memset(str,0,len + 1);
            strcpy(str,s.str);
        }
        Str(Str &&s)
        {
            cout<<"移动构造函数..."<<endl;
            str = NULL;
            str = s.str;
            s.str = NULL;
        }
        ~Str()
        {
            cout<<"析构函数"<<endl;
            if(str != NULL)
            {
                free(str);
                str = NULL;
            }
        }
};
int main()
{
    char value[] = "I love zx";
    Str s(value);
    vector<Str> vs;
    //vs.push_back(move(s));
    vs.push_back(s);
    cout<<vs[0].str<<endl;
    if(s.str != NULL)
        cout<<s.str<<endl;
    return 0;
} 
移动构造函数应用最多的地方就是STL中(原文详解移动构造函数)

 

https://www.cnblogs.com/qingergege/p/7607089.html

移动构造函数应用最多的地方就是STL中(原文详解移动构造函数)

上一篇:Android Studio打包全攻略


下一篇:涛哥:Qt安卓-5.12环境搭建