C++ 关于复制、移动构造函数和移动、复制 赋值运算符的重载问题;

可以取地址的是左值,左值在内存中不在寄存器;int a; char b; a,b 都是左值;

去不了地址的都是右值,右值不在内村中实在寄存器内部;  int c= a+b ;"a+b" 就是一个右值

move()可以实现将一个左值转换为右值的功能

// std::swap
#include <iostream>
#include <vector> // std::vector
#include <algorithm>
using namespace std;
class A
{
    int *p;

public:
    A(int value) : p(new int(value))
    {
        cout << "create obj  " << p << endl;
    }

    ~A()
    {

        std::cout << "delete pointer:  " << p << std::endl;
        //查看析够函数删除了哪个指针
        if (p != nullptr)
        {
            delete p;
        }
    }

    A(A &&a)
    {
        if (this != &a)
        {
            p = a.p;
            a.p = nullptr;
            cout << " move  " << p << endl;
        }
        else
        {
            cout << "move self" << endl;
        }
    }
    A(const A &a)
    {
        if (this != &a)
        {
            p = new int(233);
            *p = *(a.p);
            cout << "  copy " << p << endl;
        }
        else
        {
            cout << "copy self" << endl;
        }
    }

    A &operator=(A &&a)
    {
        if (this != &a)
        {
            p = a.p;
            a.p = nullptr;
            cout << " && ==  move" << p << endl;
            return *this;
        }
        else
        {
            cout << "move = self" << endl;
        }
    }
    A &operator=(const A &a)
    {
        if (this != &a)
        {
            p = new int(233);
            *p = *(a.p);
            cout << " & == copy" << p << endl;
        }
        else
        {
            cout << "copy = self" << endl;
        }
        return *this;
    }

    void print(A &a)
    {
        cout << "print " << (a.p) << endl;
       // A b = a;
        //a.p=nullptr;
    }

};
//总结:  只有变量之间赋值才会使用赋值运算符“=”
//        使用一个对象初始化新建对象都是使用移动或者是复制构造函数;

int main()
{
    vector<A> vec;
    {
        A a(1);
        //A b(2);
        //A b(move(a)); //移动构造函数
        //A e(a);//复制构造函数
        //A d =move(a);//移动构造函数
        //A c=a; //复制构造函数

        // a.print(a);
        // getchar();
        
        //std::swap(a,b);

        //A c(2);
        //c=a;//使用了复制赋值函数
        //c =move(a); //使用了移动赋值函数
        //c.print(c);

        //自己移动自己和自己复制自己测试
        //a=(move(a)); //如果没有if(this!=&a)则会产生错误
        //a = a;//

        //容器测试:容器可以使用复制构造函数也可以使用移动构造函数给容器添加元素
        //vec.push_back(move(a)); //使用了移动构造函数
        //vec.push_back(a);//使用了复制构造函数
    }
    getchar();
   
}

猜你喜欢

转载自blog.csdn.net/u010261063/article/details/104741000