0

我不明白为什么为什么移动构造函数没有被调用,而移动赋值能够,而如果我使用X行中的移动函数,它用于调用移动构造函数。任何人都可以告诉什么是调用移动构造函数的方式或语法。当移动构造函数将在C++ 11中调用?

#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; 
} 

OUTPUT:

原始拷贝东西 东西 原料没什么 默认复制移动分配析构函数 东西 析构函数 析构函数 析构函数 析构函数

回答

1

它的复制省略的第二个变体解释这里:http://en.cppreference.com/w/cpp/language/copy_elision

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

注意-fno-elide-constructors,它禁用克优化++。

输出:

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

好争论接受!但是,请你告诉我如何避免构造函数的影响。我的意思是在编译过程中需要给出什么论点。 g ++ -std = C++ 11 ?? copies.cpp -o副本 – user3798283

+0

嗯,它就在“注意:-fno-elide-constructor”中。正如你所看到的,输出有你的给定线。我不知道如何强制编译器在使用无名称的临时文件时不这样做。 – luk32

相关问题