c++ - Memory allocation and copy construcors -
https://stackoverflow.com/a/3278636/462608
class::class( const char* str ) { stored = new char[srtlen( str ) + 1 ]; strcpy( stored, str ); }
in case member-wise copying of stored member not duplicate buffer (only pointer copied)
but here memory being allocated new
. why still said pointer copied not whole buffer?
in class class
have pointer named stored
. when instance of class
copied, e.g.
class a("hello"); class b = a; // copying
then pointer stored
copied, have 2 objects same pointer. if delete
pointer in 1 object other object still have pointer point unallocated memory.
that's why need create copy constructor:
class(const class& other) { stored = new char[strlen(other.stored) + 1]; strcpy(stored, other.stored); }
now if have above copy constructor, when copying happening in first code snippet, new string allocated, , contents other instance copied. of course, need copy-assignment operator used when assigning between 2 object instances:
class& operator=(const class& other);
Comments
Post a Comment