【问题标题】:Why does free error occurs in operator overloading?为什么运算符重载会出现free错误?
【发布时间】:2016-01-03 19:18:37
【问题描述】:

我已经为std::string 类重载了operator*,但在这种情况下:

std::string operator*(std::string a, unsigned b) //bad
{
    unsigned old_length = a.length();
    a.resize(a.length()*b);
    for(unsigned i = old_length ;i<a.length()*b; i++)
        a[i]=a[i%old_length];
    return a;
}

程序因错误而崩溃:

*** `./program' 中的错误:free():下一个大小无效(快速):0x0000000000cd20b0 *** 中止

如果我像这样重载它 - 没有错误:

std::string operator*(std::string a, unsigned b)
{
    unsigned old_length = a.length();
    std::string a2 = a;
    a2.resize(a.length()*b);
    for(unsigned i = 0 ;i<a.length()*b; i++)
        a2[i]=a[i%old_length];
    return a2;
}

那么问题出在哪里?有没有办法不创建新字符串a2?它会消耗额外的内存。

#include <iostream>
#include <string>

std::string operator*(unsigned b, std::string a)
{
    return operator*(a, b);
}

int main(int argc, char **argv)
{
    std::string a = "abcdef "; // if string contains more than 4 symbols - free error for the first case
    std::string aaaa = 4*a;

    std::cout << a << "\n" 
              << aaaa << "\n" 
              << std::endl;
    return 0;
}

【问题讨论】:

    标签: c++ string operator-overloading iteration


    【解决方案1】:

    直到a.length() * b 再次迭代(因为它在调整大小后等同于old_length * b * b)。

    条件必须是i &lt; a.length()i &lt; old_length * b

    但是为什么不使用std::string 的一些功能呢?

    std::string operator*(std::string a, unsigned b)
    {
        a.reserve(a.length() * b);
    
        for(unsigned i = 1 ; i <= b; i++)
            a += a.substr(0, a.length() / b);
    
        return a;
    }
    

    我们还有效地消除了old_length 变量(在性能方面不是那么有效,请在下面的评论中查看更好的方法)。

    【讨论】:

    • auto n = a.length(); a.reserve(n * b); while(b--) a.append(a, 0, n);return a; 应该更好...
    • 里面有一些const,是的
    【解决方案2】:

    一旦你这样做了a.resize(a.length()*b);

    a.length() 已更改。

    你的循环应该比

    for(unsigned i = old_length ;i<a.length(); i++)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 2021-12-13
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      相关资源
      最近更新 更多