C++ move 复制构造函数和 move 赋值运算符

标签 c++ class runtime-error copy-constructor move-semantics

我用 move 复制构造函数和 move 复制赋值运算符创建了一个简单的应用程序,并且在它们中的每一个上我都做了一个 cout 语句来告诉我,它们正在执行。但是在执行过程中,我没有看到 move 复制运算符的任何语句,而只看到编译器已经提供的默认语句。这是我的代码:

#include <iostream>
#include <string>
using namespace std;

class Names{
private:
    string* name;
public:
    Names(string place_name){
        cout << "Overloaded constructor" << endl;
        name = new string;
        *name = place_name;
    }
    //copy constructor
    Names(Names& cpy){
        cout << "Copy constructor" << endl;
        name = new string;
        *name = *cpy.name;
    }
    //assignment 
    Names& operator =(const Names& cpy){
        cout << "Assignment operator" << endl;
        name = new string;
        *name = *cpy.name;
        return *this;
    }
    //move constructor
    Names(Names&& cpym){
        cout << "Copy move constructor" << endl;
        name = cpym.name;
        cpym.name = NULL;
    }
    //move assignment operator
    Names& operator=(Names&& cpym){
        cout << "Copy assignment operator" << endl;
        delete name;
        name = cpym.name;
        cpym.name = NULL;
        return *this;
    }
    //destructor
    ~Names(){
        cout << "Deallocating memory" << endl;
        delete [] name;
    }
};

int main(){
    Names nme("Bob");
    Names copin("something");
    copin = nme;
    system("pause");
    return 0;
} 

这是输出

Output screen

所以主要的问题是

1) Why isn't the cout statement being show for the move constructor?
2) Is my declaration for move constructor correct

谢谢你。

最佳答案

move 构造函数和 move 赋值运算符需要使用 std::move 才能工作。请参阅下面我的主要功能:

Names A(Names name) {
    return name;
}
int main(){
    Names nme("Bob");
    Names copin("something");
    cout << "before std::move(nme);" << endl;
    copin = std::move(nme);
    cout << "before std::move(GetName());" << endl;
    Names tom = std::move(nme);
    cout << "before A(Names(\"dick\");" << endl;
    // move constructor is also called when using temp rvalue
    Names dick = A(Names("dick"));
    system("pause");
    return 0;
}

输出:

Overloaded constructor
Overloaded constructor
before std::move(nme);
Copy assignment operator
before std::move(GetName());
Copy move constructor
before A(Names("dick");
Overloaded constructor
Copy move constructor
Copy constructor
Deallocating memory
Deallocating memory
Press any key to continue . . .

还有一个问题,你的析构函数不应该删除[] name,只删除name;

关于C++ move 复制构造函数和 move 赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22213163/

相关文章:

java - 创建枚举与创建 Java 类有什么区别?

class - 在 Dart 中不继承静态变量的基本原理是什么?

cocoa-touch - 从应用商店下载时,应用崩溃

c - C 中的依赖错误

c++ - 如何从派生类访问类的成员-C++

java - ArrayList运行时错误

c++ - 如何在opencv中绘制带有蒙版图像的矩形?

c++ - 为什么我要调用一个函数名包裹在括号中的函数?

c++ - C++中的事件管理

c++ - 编写用于创建 vector 长度 vector 的算法