为什么我的move构造函数无法在C ++中工作

时间:2019-01-30 14:20:08

标签: c++ move-semantics

我目前正在学习C ++,并且达到了所谓的move构造函数的地步。我知道,只要我将一个对象分配给另一个变量,它们就可以自动调用以避免不必要的复制...对吧?

我正在关注一个YouTube教程,并试图从视频1:1中复制代码。

DynamicArray.h

class DynamicArray {
private:
    int size;
    int* data;
public:
    DynamicArray(int size);
    DynamicArray(const DynamicArray &other);
    DynamicArray(DynamicArray &&other) noexcept;
    ~DynamicArray();
    int getSize();
    int get(int index);
    void set(int index, int value);
    DynamicArray operator+(const DynamicArray &other);
};

DynamicArray.cpp

DynamicArray::DynamicArray(int size) : size(size) {
    data = new int[size];
}
DynamicArray::DynamicArray(const DynamicArray &other) {
    size = other.size;
    data = new int[size];
}
DynamicArray::DynamicArray(DynamicArray &&other) noexcept {
    std::cout << "move" << std::endl; // this is never printed
    data = other.data;
    size = other.size;
    other.data = nullptr;
}
DynamicArray::~DynamicArray() {
    delete[] data;
}
int DynamicArray::getSize() {
    return size;
}
int DynamicArray::get(int index) {
    return data[index];
}
void DynamicArray::set(int index, int value) {
    data[index] = value;
}
DynamicArray DynamicArray::operator+(const DynamicArray &other) {
    if (size != other.size) {
        std::cerr << "DynamicArray's size do not match." << std::endl;
        exit(10);
    }
    std::cout << "Adding DynamicArrays" << std::endl;

    DynamicArray retVal(size);
    for (int i = 0; i < size; i++) {
        retVal.data[i] = data[i] + other.data[i];
    }

    return retVal;
}

main.cpp

DynamicArray a(3);
a.set(0,5);
a.set(1,2);
a.set(2,8);

DynamicArray b(3);
a.set(0,7);
a.set(1,5);
a.set(2,2);

DynamicArray c = a + b; // shouldn't the move be called here?
DynamicArray d = DynamicArray(4); // or here?
DynamicArray e = d; // or at least here?

控制台注销为

Adding DynamicArrays
7

我期望在“添加DynamicArrays”打印之前或之后进行“移动”打印。

0 个答案:

没有答案