<分区>
我很好奇为什么拷贝构造函数对于我自己定义类的动态分配如此重要。
我正在实现具有动态分配的低级 c 字符串类,这是我的类的快速 View
class String
{
private:
char * buf;
bool inBounds( int i )
{
return i >= 0 && i < strlen(buf);
}
static int strlen(const char *src)
{
int count = 0;
while (*(src+count))
++count;
return count;
}
static char *strcpy(char *dest, const char *src)
{
char *p = dest;
while( (*p++ = *src++));
return dest;
}
static char* strdup(const char *src)
{
char * res = new_char_array(strlen(src)+1);
strcpy(res,src);
return res;
}
static char * new_char_array(int n_bytes)
{
return new char[n_bytes];
}
static void delete_char_array( char* p)
{
delete[] p;
}
public:
/// Both constructors should construct
/// this String from the parameter s
String( const char * s = "")
{
buf = strdup(s);
}
String( String & s)
{
buf = strdup(s.buf);
}
void reverse()
{
}
void print( ostream & out )
{
out << buf;
}
~String()
{
delete_char_array(buf);
}
};
ostream & operator << ( ostream & out, String str )
{
str.print(out);
return out;
}
我知道 strdup() 函数的部分并不正确,但我只是在做一些测试。
我的问题是如果我没有复制构造函数而我的 main() 是
int main()
{
String b("abc");
String a(b);
cout << b << endl;
return 0;
}
编译器会告诉我double free or corruption (fasttop)
我找到了关于这个问题的一些答案并查看了三大规则。
如果我有复制构造函数,你们能告诉我为什么我的代码没有任何错误吗?双重释放或损坏(fasttop)的错误是什么意思?