当在C ++ 11中调用move构造函数时?

时间:2016-04-28 13:30:04

标签: c++11 rvalue-reference move-constructor move-assignment-operator

我无法理解为什么移动赋值能够在移动赋值能够的同时调用移动构造函数的原因如果我在行X中使用移动函数,它用于调用移动构造函数。任何人都可以告诉调用移动构造函数的方式或语法。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <memory>
using namespace std;
class String
{
    char *s;
    int len;
    public:
    String():s(nullptr),len(0){ cout<<"Default "; }
    String(char *p)
    {
        if(p)
        {
            len = strlen(p);
            s = new char[len];
            strcpy(s,p);
        }
        else
        {
            s = nullptr;
            len = 0;
        }
        cout<<"Raw ";
    }
    String(String &p)
    {
        if(p.s)
        {
            len = strlen(p.s);
            s = new char[len];
            strcpy(s,p.s);
        }
        else
        {
            s = nullptr;
            len = 0;
        }
        cout<<"Copy ";
    }
    String & operator = (const String & p)
    {
        if(this != &p)
        {
            delete []s;
            s = nullptr;
            len = 0;
            if(p.len)
            {
                len = p.len;
                s = new char[len];
                strcpy(s,p.s);
            }
        }
        cout<<"Assignment ";
        return *this;
    }
    String( String && p):s(nullptr),len(0)    // move constructor 
    {
        len = p.len;
        s = p.s;
        p.s = nullptr;
        p.len = 0;
        cout<<"Move Copy ";
    }
    String & operator = (String && p)       // move assignment
    {
        if(this != &p)
        {
            delete []s;
            len = 0;
            s = nullptr;
            if(p.len)
            {
                len = p.len;
                s = p.s;
                p.s = nullptr;
                p.len = 0;
            }
        }
        cout<<"Move Assignment ";
        return *this;
    }
    ~String() { delete []s; cout<<"Destructor \n"; }
    void show() { cout<<s<<endl; }
};
int main()
{
   String s1("Something ");
   String s2(s1);
   s1.show();
   s2.show();
   String s4(String("Nothing "));       // Line X
   s4.show();
   String s5;
   s5 = String(s2);
   s5.show();
   return 0;
}

输出:

Raw Copy Something 某物 原始没什么 默认复制移动分配析构函数 某物 析构函数 析构函数 析构函数 析构函数

1 个答案:

答案 0 :(得分:1)

这是此处解释的副本省略的第二个变体:http://en.cppreference.com/w/cpp/language/copy_elision

http://coliru.stacked-crooked.com/a/17f811a0be4ecba3

注意-fno-elide-constructors,它会禁用g ++中的优化。

输出:

Copy Something 
Something 
Raw Move Copy Move Copy Destructor 
Destructor 
Nothing 
Default Copy Move Assignment Destructor 
Something 
Destructor 
Destructor 
Destructor 
Destructor