1

以下代码在 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 读取无效。我猜有一些堆栈损坏,但对于我的生活,我找不到它。

有趣的是,删除标记为“删除我”的行会使问题消失。添加endlto也是如此write。有任何想法吗?

4

1 回答 1

9
ostream & operator <<(ostream & o, const mystring & ms) {
  ms.write(o);
};

这会导致未定义的行为,因为它不返回任何内容。此外,命名空间级别的空声明 (";") 是完全没有必要的(并且在旧 C++ 标准中曾经是非法的)。

于 2014-08-04T11:28:38.503 回答