c++ - 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++。
解决方案
推荐阅读
- git - 您可以仅使用 IDX 和 PACK 文件重建 repo 吗?
- c++ - 一元和二元运算符之间的性能差异
- go - go数组存储为字符串-如何转换为数组
- google-app-engine - 如何为 nodejs Google App Engine 项目制作基本的 app.yaml 文件
- cross-browser - 为什么我的字体大小在 Firefox 和 chrome 移动浏览器上显示不同?
- kubelet - Microk8s 将 kubelet.service 保存在哪里?
- typescript - 基于可写性的 Typescript 条件类型
- javascript - 在同一主机和端口上侦听两次不会触发错误
- typescript - TS:将函数分配给具有泛型类型的`const`
- perl - 在 Perl 中正确使用 IPC::Run