【问题标题】:c++ polynomial copy-constructor and ostream override cause memeory leaks?!c++ 多项式复制构造函数和 ostream 覆盖导致内存泄漏?!
【发布时间】:2015-06-18 03:42:08
【问题描述】:

您好,我正在研究 C++ 中的多项式类。到目前为止,一切都运作良好。但是现在我遇到了一个我根本无法发现的错误:/

多项式.cpp

// copy-constructor
    Polynomial::Polynomial(const Polynomial &p){
        size = p.size;
        buffer = p.buffer;
        poly = new double(buffer);

        for (int i = 0; i < size; ++i) poly[i] = p[i];
        for (int i = size; i < buffer; ++i) poly[i] = 0;
    }

// output stream override | it's a non-member function
ostream& operator<<(ostream& os, const v1::Polynomial& p){      
    int degree = p.degree();
    stringstream ss;

    if (degree == 0) ss << '0';
    else if (degree > 0){
        ss << '(';
        for (int i = degree; i >= 0; --i){
            ss << p[i];
            ss << "x^";
            ss << i;
            if (i > 0)
                ss << " + ";
        }
        ss << ')' << endl;

    }
    os << ss.str();
    return os;
}

这就是我调用复制构造函数的方式:

// note: printing 'a' itself does not cause problems...
v1::Polynomial b(a);    
cout << "Polynomial b: " << b << " degree: " << b.degree() << endl;;

Visual Studio 的堆栈日志显示它位于第 23 行(此处:此行上方的行,我实际上想要打印 'b'),然后它继续调用一些堆函数等。 在没有调试的情况下运行程序(通过 cmd)会导致 APPCRASH,其中“多项式 b:”是最后显示的内容。

不幸的是,我不知道如何在 Visual Studio 中调试,我习惯于在 linux 中使用 valgrind,我目前还没有设置:/

有人知道吗?还是您需要更多信息?

无论如何,非常感谢您 =)

【问题讨论】:

  • 而这里分配的内存poly = new double(buffer);实际上被删除了? “很遗憾,我不知道如何在 Visual Studio 中调试” F5 IIRC.
  • 如果可能发生崩溃,您需要提供degree() 的代码。
  • 最好是编写代码,这样它根本不需要自定义复制构造函数。

标签: c++ operator-overloading copy-constructor ostream


【解决方案1】:
poly = new double(buffer);

在这里您分配一个单个 double 并将其设置为buffer。你可能是说

poly = new double[buffer];

或任何你想要的尺寸。

很多更好的解决方案是使用std::vector 而不是原始数组。你可以用=复制它,用std::vector::resize调整它的大小,用std::vector::reserve保留更多空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    相关资源
    最近更新 更多