以下代码在 Debian 7 上的 g++ 4.7.2-5 上编译并正常工作。
#include <iostream>
#include <string.h>
using namespace std;
class mystring {
char * buf;
static char * dupbuf(const char * buf) {
char * result = new char[strlen(buf) + 1];
strcpy(result, buf);
return result;
}
public:
mystring(const char * o)
: buf(dupbuf(o)) {}
~mystring() { delete[] buf; }
mystring(const mystring &) = delete;
mystring & operator=(const mystring&) = delete;
void write(ostream & o) const {
if (!buf) { exit(1); } // remove me
o << buf;
}
};
ostream & operator <<(ostream & o, const mystring & ms) {
ms.write(o);
};
int main() {
mystring m("hello");
cout << m << endl;
return 0;
}
...除非您使用 -O2 或更高版本进行编译。然后它会出现段错误,并且 valgrind 声称从 0x0 读取无效。我猜有一些堆栈损坏,但对于我的生活,我找不到它。
有趣的是,删除标记为“删除我”的行会使问题消失。添加endl
to也是如此write
。有任何想法吗?