我有以下代码:
Class Chain
Run Code Online (Sandbox Code Playgroud)
同
char* c;
Run Code Online (Sandbox Code Playgroud)
作为唯一的公共因素
istream& operator>>(istream& i, Chain& s) {
delete [] s.c;
const int L = 256;
char *t = new char[L];
i.getline(t,L);
s.c = t;
return i;
}
ostream& operator<<(ostream& o, Chain s) {
o << s.c;
return o;
}
#include <iostream>
#include "Chain.h"
using namespace std;
int main(){
Chain id;
cin >> id;
cout << id;
cout << id;
Run Code Online (Sandbox Code Playgroud)
在Xubuntu(最新版本)上的Eclipse IDE下运行代码后,我收到以下错误:
[...]双重免费或损坏中的错误(上):0x00000000008fd290***
可能有什么不对?
ostream& operator<<(ostream& o, Chain s) {
Run Code Online (Sandbox Code Playgroud)
这不是一个参考s,它正在构建一个完整的副本,可能有一个删除所用内存的析构函数.因为你两次调用它,它会被删除两次.