【发布时间】: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