Untitled

 avatar
unknown
c_cpp
4 years ago
1.4 kB
12
Indexable
#include <iostream>

class A{
public:
    int* arr;
    int b;
    A() = delete;
    explicit A(const int c) {
        arr = new int[c];
        b = c;
        for (int i = 0; i < b; i++)
            arr[i] = i;
    }
    A(A const& B) {
        std::cout << "copy constructor was called" << std::endl;
        this->b = B.b;
        this->arr = new int[b];
        for (int i = 0; i < b; i++) {
            this->arr[i] = B.arr[i];
        }
    }
    explicit A(A&& B) {
        std::cout << "move constructor was called" << std::endl;
        this->b = B.b;
        this->arr = B.arr;
        // 防止 B.arr 和 A.arr 指向相同的数据
        // B.arr 析构时出错
        B.arr = nullptr;
    }
    A& operator=(const A& B) {
        std::cout << "copy assignment was called" << std::endl;
        this->b = B.b;
        this->arr = new int[b];
        for (int i = 0; i < b; i++) {
            this->arr[i] = B.arr[i];
        }
        return *this;
    }
    A& operator=(A&& B) {
        std::cout << "move assignment was called" << std::endl;
        this->b = B.b;
        this->arr = B.arr;
        B.arr = nullptr;
        return *this;
    }
    virtual ~A() {
        std::cout << "destory" << std::endl;
    }
};

A create_data() {
    A a(10);
    return a;
}

int main () {
    // A a(10);
    // a = create_data();
    A a = create_data();
    std::cout << a.arr[2] << std::endl;
    return 0;
}
Editor is loading...