-3

I'm having a little trouble with Copy Constructor.

I have a class, which contains two structures, and two pointers to the first structure ( let's just say I'm having a Linked List of first structure, and each contains a linked list of the second structure ). They all seem to work fine. But ...

When I make another instance of the class using the copy constructor ( does a deep copy, every element is copied, so each instance has it's own linked lists ) using

MyClass a,b; // Operations with a b ( a );

it all works ok. But then...

MyClass a,b; // Operations with a b = a;

also seems to work, but then my destructor goes amok, and tries to free some element multiple times, sending this:

* Error in `./a.out': double free or corruption (!prev): 0x000000000258a540 *

along with ==Backtrace== and ==Memory Map==, ending killing my program by SIGABRT signal.

So, when the copy constructor works fine and is present, what is wrong with assignment? Should I override the operator= ?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Michal Kučera
  • 223
  • 1
  • 11

3 Answers3

2

If you do not have defined a assignment operator explicitly, it is obvious that your code is broken. A implicit assignment operator does member-wise assignment of each data member from the assigned object. If you have member variables that e.g. live on the heap the standard implicit assignment operator does not do a deep copy and only copies the pointer values.

OnWhenReady
  • 939
  • 6
  • 15
2

The copy constructor is used when you create a new object, specifying an object to copy, so

MyClass b(a); (MyClass b = a; is the same)

Uses the copy constructor.

The assignment operator changes the value of an existing object, so in your case:

MyClass b;

Creates b and

b = a;

uses the assignment operator, which you haven't defined.

parkydr
  • 7,596
  • 3
  • 32
  • 42
0

In C++, the copy constructor and the copy assignment operator are closely related. In fact, the idiomatic implementation of the copy assignment operator is implemented in terms of the copy constructor, which means that the copy assignment operator calls it internally. This is called the copy-and-swap idiom.

It will also prevent strange errors cause otherwise by accidental self-assignment.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62