首页 > 解决方案 > C++ 复制赋值运算符

问题描述

我正在尝试使用复制赋值构造函数、模板和智能指针进行练习

#include <iostream>

template <typename T>
class Stack {
private:
    enum {MAX = 10};
    std::unique_ptr<T[]> pitems;
    int size;
    int top;
public:
    Stack(int n = 10){
        size = n;
        top = -1;
        T* items = new T[n];
        pitems = std::make_unique<T[]>(size);
    }

    Stack(const Stack & st): size(st.size), top(st.top){
        //Costruttore di copia
        std::unique_ptr<T[]> pitems = std::make_unique<T[]>(size);
        memcpy(pitems.get(), st.pitems.get(), size);
    }

    ~Stack(){
        pitems.reset();
    }

    bool isempty(){
        if(top == -1) return true;
        return false;
    };
    bool isfull(){
        if(top == size-1) return true;
        return false;
    };
    // push() returns false if stack already is full, true otherwise
    bool push(const T & item){
        if(isfull() == false){
            pitems[top] = item;
            top++;
            return true;
        }
        return false;
    } // add item to stack
    // pop() returns false if stack already is empty, true otherwise
    bool pop(T & item){
        if(isempty()) return false;
        item = pitems[top-1];
        top--;
        return true;
    }

    Stack& operator=(const Stack & st){
        if(this != &st){
            this->size = st.size;
            this->top = st.top;

            this->pitems.reset(new T[this->size]);
            memcpy(this->pitems.get(), st.pitems.get(), st.size);
        }
    }
};


int main() {
    Stack<int> s = Stack<int>(2);
    std::cout << s.isempty() << std::endl;
    s.push(3);
    int p;
    std::cout << s.isfull() << std::endl;
    s.pop(p);
    std::cout << p << std::endl;

    Stack<int> j;
    j = s;
    std::cout << j.pop(p) << std::endl;

    return 0;
}

但是当我尝试在 s 中复制 j 时,我从编译器得到 EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) ,我不明白为什么。此外,我不明白为什么,当我用编译器检查它时,复制赋值运算符被调用了两次。抱歉这个可能很愚蠢的问题,但我几周前开始学习 C++。

标签: c++

解决方案


推荐阅读