0

https://stackoverflow.com/a/3278636/462608

Class::Class( const char* str )
{
    stored = new char[srtlen( str ) + 1 ];
    strcpy( stored, str );
}

in this case member-wise copying of stored member will not duplicate the buffer (only the pointer will be copied)

But here the memory is being allocated by new. Then why is it still said that only the pointer will get copied not the whole buffer?

Community
  • 1
  • 1
Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

3 Answers3

4

In your class Class you have a pointer named stored. When an instance of Class is copied, like e.g.

Class a("hello");
Class b = a;  // Copying a

then the pointer stored will be copied, so then you have two objects with the same pointer. Then if you delete the pointer in one object then the other object still have its pointer which will now point to unallocated memory.

That's why you need to create a copy constructor:

Class(const Class& other)
{
    stored = new char[strlen(other.stored) + 1];
    strcpy(stored, other.stored);
}

Now if you have the above copy constructor, when a copying is happening like in my first code snippet, then a new string will be allocated, and the contents from the other instance will be copied. Of course, you also need a copy-assignment operator to be used when assigning between two object instances:

Class& operator=(const Class& other);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Your class have a member who is a pointer named stored. When an instance of the Class is copied:

Class foo( "str" );
Class bar( foo );   // Copy

with the default copy-constructor, it will copy the members of the class, in that case, it will copy stored who is a pointer, not its content.

That's why, it you need to redefine here a copy-constructor and an operator= or copy-assignment operator like:

Class::Class( const Class& another )
{
    stored = new char[strlen(another.stored) + 1];
    strcpy( stored, another.stored );
 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Copy the buffer
}

void Class::operator = ( const Class& another )
{
    char* temp = new char[strlen(another.stored) + 1];
    strcpy( temp, another.stored);
 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Copy the buffer
    delete[] stored;
    stored = temp;
}

Otherwise, when the first instance (lets say a) is destructed, you will have an Undefined behaviour when you will try to access to the stored member of b.

Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62
0

Because your stored variable is a plain pointer(address of a buffer, effectively). So when you copy an object this pointer(address) is copied to another object. So you end up with two objects pointing to the same location(buffer). To have correct behavior you need to either use some smart buffer(like std::vector) or write copy ctor and copy buffer manually inside it. newdeals with it in no way.

ixSci
  • 13,100
  • 5
  • 45
  • 79