c++ - What does Copy constructor do for dynamic allocations -
this question has answer here:
- what rule of three? 8 answers
i curious why copy constructor important dynamic allocation of own defined class.
i implementing low-level c-string class dynamic allocations , here quick view of class
class string { private: char * buf; bool inbounds( int ) { return >= 0 && < 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 /// string 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; }
i know part of strdup() function not correct doing tests.
my problem if not have copy constructor , main()
int main() { string b("abc"); string a(b); cout << b << endl; return 0; }
the compiler tell me double free or corruption (fasttop)
, find answers question , see big 3 rules.
can guys tell me why code works without errors if have copy constructor , error of double free or corruption (fasttop) means?
if don't define copy constructor, compiler insert 1 you. default copy constructor copy data members, both instances of string point same area of memory. buf
variable hold same value in each instance.
therefore when instances go out of scope , destroyed, both attempt release same area of memory, , cause error.
Comments
Post a Comment