0

我无法理解为什么移动构造函数没有被调用,而移动赋值能够,而如果我在 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 Something Raw Nothing 默认复制 Move 赋值 析构函数 析构函数 析构函数 析构函数 析构函数

4

1 回答 1

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 
于 2016-04-28T13:46:15.140 回答