以下代码在 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 读取无效。我猜有一些堆栈损坏,但我这辈子都找不到它。
有趣的是,删除标记为“remove me”的行会使问题消失。将 endl
添加到 write
也是如此。有什么想法吗?
最佳答案
ostream & operator <<(ostream & o, const mystring & ms) {
ms.write(o);
};
这会导致未定义的行为,因为它不返回任何内容。此外,命名空间级别的空声明(“;”)是完全没有必要的(并且在旧的 C++ 标准中曾经是非法的)。
关于c++ - 使用 -O3 编译时出现奇怪的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25117385/